Created
March 17, 2017 15:24
-
-
Save bobfirestone/7ecccda3d54bafda586fbe54d7d2f0e1 to your computer and use it in GitHub Desktop.
Part 2 of my submission for the shapes portion of the 1st assignment of FUNCTIONAL PROGRAMMING IN ERLANG THE UNIVERSITY OF KENT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(bits). | |
-export([bits/1,tests/0]). | |
bits(N) when N >= 0 -> | |
% convert N into a base 2 list then back into a base 10 number | |
bits(list_to_integer(integer_to_list(N,2)),0). | |
bits(0, Acc) -> Acc; | |
bits(N,Acc) -> | |
% divide N by 10 to pass through to the recursive function | |
% divide N by 2 to determine if 1 or 0 and add to the Accumulator | |
bits(trunc(N/10), Acc + (N rem 2)). | |
tests() -> | |
% test cases {Number to convrt, expected total} | |
run_cases([{0,0},{1,1},{2,1},{3,2},{4,1},{5,2},{6,2},{7,3},{8,1},{9,2},{10,2}]). | |
run_cases([]) -> | |
complete; | |
run_cases([H|T]) -> | |
test(H), | |
run_cases(T). | |
test({N,Acc}) -> | |
Spec = (Acc == bits(N)), | |
test_output_formatter(N, Spec). | |
test_output_formatter(Name, Spec) -> | |
io:format(integer_to_list(Name) ++ ": " ++ atom_to_list(Spec) ++ "\n"). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment