I am trying to learn Erlang using Karate Chop Kata . I translated the runit test supplied in kata into an eunit test and encoded a small function to complete the task.
-module(chop).
-export([chop/2]).
-import(lists).
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
chop_test_() -> [
?_assertMatch(-1, chop(3, [])),
?_assertMatch(-1, chop(3, [1])),
?_assertMatch(0, chop(1, [1])),
....several asserts deleted for brevity...
].
-endif.
chop(N,L) -> chop(N,L,0);
chop(_,[]) -> -1.
chop(_, [],_) -> -1;
chop(N, L, M) ->
MidIndex = length(L) div 2,
MidPoint = lists:nth(MidIndex,L),
{Left,Right} = lists:split(MidIndex,L),
case MidPoint of
_ when MidPoint < N -> chop(N,Right,M+MidIndex);
_ when MidPoint =:= N -> M+MidIndex;
_ when MidPoint > N -> chop(N,Left,M)
end.
The ok.Running test compiles, however, it gives (among other things) the following failure:
::error:badarg
in function erlang:length/1
called as length(1)
in call from chop:chop/3
I tried different permutations of chop declaration (N, [L], M) .... and used length ([L]), but couldn't solve this problem. Any suggestions are welcome.
ps. As you may have guessed, I am zero when it comes to Erlang.