-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathproblem2.erl
47 lines (36 loc) · 1.08 KB
/
problem2.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
-module(problem2).
-include_lib("eunit/include/eunit.hrl").
-export([problem2/0]).
-import(euler_helper,[fib/1]).
even(X) ->
X rem 2 == 0.
fibsum(Invariant, Termcond) ->
fibsum(1, Invariant, Termcond).
fibsum(Y, Invariant, Termcond) ->
X = fib(Y),
case Termcond(X) of
true ->
case Invariant(X) of
true ->
fib(Y) + fibsum(Y+1, Invariant, Termcond);
false ->
fibsum(Y+1, Invariant, Termcond)
end;
false ->
0
end.
problem2() ->
fibsum(fun even/1,fun(X) -> X < 4000000 end).
%% tests
even_test() ->
?assert(even(2)).
even_not_test() ->
?assertNot(even(1)).
fibsum_simple_test() ->
?assertEqual(6,fibsum(fun(_) -> true end, fun(X) -> X < 4 end)).
fibsum_longer_test() ->
?assertEqual(11,fibsum(1, fun(_) -> true end, fun(X) -> X < 6 end)).
fibsum_step_test() ->
?assertEqual(6,fibsum(1,fun(_) -> true end, fun(X) -> X < 4 end)).
fibsum_invariant_test() ->
?assertEqual(1,fibsum(1,fun(X) -> X == 1 end, fun(X) -> X < 4 end)).