Erlang filter list using lists:keyfind partial string -
i new erlang
i have list as:
list = [[{name, <<"redcar1">>}, {turbo, true}], [{name, <<"redcar2">>}, {turbo, true}], [{name, <<"greencard">>}, {turbo, false}]]. now want filter "red" cars
i tried using:
filtercar() -> myf = fun(list) -> case lists:keyfind(name, 1, list) of {name, <<"red", _rest/binary>>} -> true: _ -> false end end, myf. then
lists:filter(myf, list), it works perfectly.
now want create generic function filter, like:
myfilter(value, list) -> case lists:keyfind(name, 1, list) of {name, <<value, _rest/binary>>} -> true; _ -> false end. but when try execute function got [] empty list.
i sure problem when try pass value because if replace
{name, <<value, _rest/binary>>} with
{name, <<"red", _rest/binary>>} it works.
my aim find string start car in ignore case.
you need indicate 2 more things use general value in binary: it's binary, , size of binary.
filtercar(value) when is_binary(value) -> myf = fun(list) -> size = byte_size(value), case lists:keyfind(name, 1, list) of {name, <<value:size/binary, _rest/binary>>} -> true; _ -> false end end, myf. first changed filterguard take 1 argument, value, pattern want for. use guard on function ensure value binary. inside internal fun first retrieve size of value via byte_size/1, need can set expected field size in matching binary. leads key change, <<value:size/binary, _rest/binary>>: set expected size of value field, , define binary field.
with change in place, can apply list variable, passing <<"red">> value:
1> lists:filter(filtercar(<<"red">>), list). [[{name,<<"redcar1">>},{turbo,true}], [{name,<<"redcar2">>},{turbo,true}]]
Comments
Post a Comment