Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List is conceived as integer by length function

Tags:

list

erlang

I'm trying to learn Erlang using the Karate Chop Kata. I translated the runit test supplied in the kata to an eunit test and coded up a small function to perform the task at hand.

-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.

Compiles ok.Running the test however gives, (amongst others) the following failure:

::error:badarg
 in function erlang:length/1
  called as length(1)
 in call from chop:chop/3

I've tried different permutations of declaring chop(N,[L],M) .... and using length([L]) but have not been able to resolve this issue. Any suggestions are welcome.

ps. As you might have guessed I'm a nube when it comes to Erlang.

like image 613
Bas Bossink Avatar asked Jul 26 '26 07:07

Bas Bossink


1 Answers

So I'm pressed for time at the moment, but the first problem I see is that

chop(N,L) -> chop(N,L,0);
chop(_,[]) -> -1.

is wrong because chop(N,L) will always match. reverse the clauses and see where that gets you.

Beyond that, in the case of the 1 element list, nth(0, [1]) will fail. I feel like these lists are probably 1-indexed.

like image 158
Ben Hughes Avatar answered Jul 28 '26 07:07

Ben Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!