The list is designed as an integer by length function

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.

+3
source share
4 answers

So, I am now clicking on the time, but the first problem that I see is that

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

, chop (N, L) . , .

, 1- nth (0, [1]) . , , , 1-.

+3

erlang: length/1 .

length (1), 1 .

length ([1]) 1 ([1,2,3,4 [) 4 .. ..

0

, , erlang , lists:nth/2 O (1), O (N). list_to_tuple/1 . .

array.

0

, . , .

chop(_,[]) -> -1;
chop(N,L) -> 
    Array = array:from_list(L),
chop(N,Array, 0, array:size(Array)-1).
chop(N, L, K, K) -> 
    Element = array:get(K,L),
    if 
        Element == N -> K; 
        true -> -1
    end;
chop(_, _, K, M) when M < K -> -1;
chop(N, L, K, M) ->
    MidIndex = K + ((M - K) div  2),
    MidPoint = array:get(MidIndex,L),
    case MidPoint of 
        N -> MidIndex;
        _ when MidPoint < N -> chop(N,L,MidIndex+1,M);
        _ -> chop(N,L,K,MidIndex-1)
    end.
-1

Source: https://habr.com/ru/post/1711136/


All Articles