函数列表中出现异常错误:foldl/3(lists.erl,第1263行)



问题

为什么当我运行一个函数时它可以工作,但当我将它传递给lists:foldl时它不工作?


详细说明

当我在终端中运行一个特定的函数时,它会返回预期的结果。但是,如果我把这个函数传递给lists:foldl,它就会抛出一个异常。

有问题的函数是separate_socks/2

当我直接运行它时,它会返回:

> sock_merchant:separate_socks(1, #{1 => [1]}).
#{1 => [1,1]}
> sock_merchant:separate_socks(1, #{}).        
#{1 => [1]}

但当我运行test/0时,它会返回:

> sock_merchant:test().                        
** exception error: bad function separate_socks
in function  lists:foldl/3 (lists.erl, line 1263)

我的sock_merchant.erl文件包含以下内容:

% John works at a clothing store. He has a large pile of socks that he must pair
% by color for sale. Given an array of integers representing the color of each
% sock, determine how many pairs of socks with matching colors there are.
% For example, there are `n = 7` socks with colors `ar = [1,2,1,2,1,3,2]`. There
% is one pair of color 1 and one of color 2. There are three odd socks left, one
% of each color. The number of pairs is 2.
-module(sock_merchant).
-export([count_number_of_pair_of_sockets/2,
filter_socks/2,
separate_socks/2,
sock_merchant/2,
test/0,
test_sock_merchant/0]).
%% Next: number
%% Acc: map
separate_socks(Next, Acc) ->
KeyExists = maps:is_key(Next, Acc),
case KeyExists of
true ->
CurrentKeyList = maps:get(Next, Acc),
maps:update(Next, [Next | CurrentKeyList], Acc);
false -> maps:put(Next, [Next], Acc)
end.
%% Value: number
filter_socks(_, Value) ->
if Value div 2 >= 1 -> true;
true -> false
end.
%% Next: {key, [number]}
%% Acc: number
count_number_of_pair_of_sockets({_, Arr}, Acc) ->
Acc + length(Arr) div 2.
%% N: number
%% Ar: [number]
sock_merchant(_, Ar) ->
% SocksSeparatedList = #{1: [1,1], 2: [2], ...}
SocksSeparatedList = lists:foldl(separate_socks,
#{},
Ar),
SocksWithPairs = maps:filter(filter_socks,
SocksSeparatedList),
ListOfSocksWithPairs = maps:to_list(SocksWithPairs),
lists:foldl(count_number_of_pair_of_sockets,
0,
ListOfSocksWithPairs).
test_sock_merchant() ->
3 = sock_merchant(9,
[10, 20, 20, 10, 10, 30, 50, 10, 20]),
pass.
test() -> pass = test_sock_merchant().

我正在从HackerBank解决这个问题https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlistronglugs%5B%5D=面试准备工具包&playlistronglugs%5B%5D=预热

术语separate_socks本身就是一个原子。这意味着,当您调用传递separate_socks作为第一个参数的lists:foldl/3时,您只是传递一个原子,而不是lists:foldl/3所要求的函数:

SocksSeparatedList = lists:foldl(separate_socks,
#{},
Ar),

要传递函数separate_socks,请将其作为函数项传递:

SocksSeparatedList = lists:foldl(fun separate_socks/2,
#{},
Ar),

fun关键字表示一个函数,后面的/2是函数arity(其参数数(。

最新更新