no function clause matching erlang - erlang

I just picked up Erlang and I ran into a simple problem, but I have not been able to fix it or find anything about it. I'm trying to define a module that checks if an atom is in a given list. I entered the list through the Erlang shell like this:
veggies:veggieMember([cucumber,tomato,potato],tomato).
But I always get exception error: no function clause matching
Maybe I misunderstood the basics, but here is the module code I'm trying to do:
-module(veggies).
-export([veggieMember/2]).
veggieMember(veggieList,query)->
case lists:member(query, veggieList) of
true->veggieList;
false->[query|veggieList]
end.

Binding in erlang starts with a capital letter. So it should be:
-module(veggies).
-export([veggieMember/2]).
veggieMember(VeggieList,Query)->
case lists:member(Query, VeggieList) of
true -> VeggieList;
false -> [Query|VeggieList]
end.
In your example it didn't work because there is no matching function clause. Atom veggieList doesn't match list [cucumber,tomato,potato] and atom query doesn't match atom tomato.
The error itself, it one of the standard errors. It means you have made a call to function and that none of the function clauses (separated by ;) matched.

Related

Lua Pattern matching only returning first match

I can't figure out how to get Lua to return ALL matches for a particular pattern match.
I have the following regex which works and is so basic:
.*\n
This just splits a long string per line.
The equivelent of this in Lua is:
.-\n
If you run the above in a regex website against the following text it will find three matches (if using the global flag).
Hello
my name is
Someone
If you do not use the global flag it will return only the first match. This is the behaviour of LUA; it's as if it does not have a global switch and will only ever return the first match.
The exact code I have is:
local test = {string.match(string_variable_here, ".-\n")}
If I run it on the above test for example, test will be a table with only one item (the first row). I even tried using capture groups but the result is the same.
I cannot find a way to make it return all occurrences of a match, does anyone know if this is possible in LUA?
Thanks,
You can use string.gmatch(s, pattern) / s:gmatch(pattern):
This returns a pattern finding iterator. The iterator will search through the string passed looking for instances of the pattern you passed.
See the online Lua demo:
local a = "Hello\nmy name is\nSomeone\n"
for i in string.gmatch(a, ".*\n") do
print(i)
end
Note that .*\n regex is equivalent to .*\n Lua pattern. - in Lua patterns is the equivalent of *? non-greedy ("lazy") quantifier.

How to invoke Erlang function with variable?

4> abs(1).
1
5> X = abs.
abs
6> X(1).
** exception error: bad function abs
7> erlang:X(1).
1
8>
Is there any particular reason why I have to use the module name when I invoke a function with a variable? This isn't going to work for me because, well, for one thing it is just way too much syntactic garbage and makes my eyes bleed. For another thing, I plan on invoking functions out of a list, something like (off the top of my head):
[X(1) || X <- [abs, f1, f2, f3...]].
Attempting to tack on various module names here is going to make the verbosity go through the roof, when the whole point of what I am doing is to reduce verbosity.
EDIT: Look here: http://www.erlangpatterns.org/chain.html The guy has made some pipe-forward function. He is invoking functions the same way I want to above, but his code doesn't work when I try to use it. But from what I know, the guy is an experienced Erlang programmer - I saw him give some keynote or whatever at a conference (well I saw it online).
Did this kind of thing used to work but not anymore? Surely there is a way I can do what I want - invoke these functions without all the verbosity and boilerplate.
EDIT: If I am reading the documentation right, it seems to imply that my example at the top should work (section 8.6) http://erlang.org/doc/reference_manual/expressions.html
I know abs is an atom, not a function. [...] Why does it work when the module name is used?
The documentation explains that (slightly reorganized):
ExprM:ExprF(Expr1,...,ExprN)
each of ExprM and ExprF must be an atom or an expression that
evaluates to an atom. The function is said to be called by using the
fully qualified function name.
ExprF(Expr1,...,ExprN)
ExprF
must be an atom or evaluate to a fun.
If ExprF is an atom the function is said to be called by using the implicitly qualified function name.
When using fully qualified function names, Erlang expects atoms or expression that evaluates to atoms. In other words, you have to bind X to an atom: X = atom. That's exactly what you provide.
But in the second form, Erlang expects either an atom or an expression that evaluates to a function. Notice that last word. In other words, if you do not use fully qualified function name, you have to bind X to a function: X = fun module:function/arity.
In the expression X=abs, abs is not a function but an atom. If you want thus to define a function,you can do so:
D = fun erlang:abs/1.
or so:
X = fun(X)->abs(X) end.
Try:
X = fun(Number) -> abs(Number) end.
Updated:
After looking at the discussion more, it seems like you're wanting to apply multiple functions to some input.
There are two projects that I haven't used personally, but I've starred on Github that may be what you're looking for.
Both of these projects use parse transforms:
fun_chain https://github.com/sasa1977/fun_chain
pipeline https://github.com/stolen/pipeline
Pipeline is unique because it uses a special syntax:
Result = [fun1, mod2:fun2, fun3] (Arg1, Arg2).
Of course, it could also be possible to write your own function to do this using a list of {module, function} tuples and applying the function to the previous output until you get the result.

Erlang function already defined with guard clauses

Writing a recursive function, I want one fn that executes when the list has elements and another when it is empty:
transfer(Master, [H|Tail]) ->
Master ! {transfer, H},
transfer(Master, Tail).
transfer(_Master, []) ->
nil.
The problem I'm getting is src/redis/redis_worker.erl:13: function transfer/2 already defined. I understand it is upset about two functions with the same name and arity, but these two should be different.
The problem is that clauses of a function need to be separated by a semicolon instead of a period.
transfer(Master, [H|Tail]) ->
Master ! {transfer, H},
transfer(Master, Tail); % use semicolon here, not period
transfer(_Master, []) ->
nil.
When you use a period to terminate the clause, the compiler considers that function's definition to be complete, so it sees your code as two separate functions instead of different clauses of the same function.
See the Erlang reference for Function Declaration Syntax for more details.
You need to use a semicolon instead of a colon to separate the two function clauses.

Can match specifications be used only for tracing and selecting from ets tables? Can they be used in a case expression?

Is there a way to use a match specification to select between different clauses of a function? I've seen match specifications used only for either tracing or matching entries in ets tables.
Example of what I want to do:
In user supplied file:
Module(m1),
Function(f1),
Guard([ %% list of match specifications follows:
%% First (and only in this case) match spec:
{ [{score, '$1', '$2', '$3'}, '$4'],
[{is_atom, '$1'}, {is_pid, '$2'}, {is_atom, '$3'}],
[true] }
]).
From this file I want to generate code. What's important for me is to be able to use the match specifications in the Guard to be able to filter out the clauses of f1 such that I can know when the first argument of f1 was a tuple of the form {score, First, Second, Third} and is_atom(First), is_pid(Second), is_atom(Third).
Is there a way for me to generate code like this:
case some_unknown_function(MatchSpec, F1Args) of
true ->
%% f1's clause matches the MatchSpec
;
false ->
%% f1's clause does not match the MatchSpec
end.
Any help would be much appreciated. Thanks.
Take a look at ets:match_spec_compile/1 and ets:match_spec_run/2, they do exactly what you want.

Why no dynamic bit pattern in function argument?

I am experimenting with bit pattern matching in Erlang:
-module(test).
-export([test/2]).
%test(P,<<X:P,0:1>>) ->
% X.
test(P,X) ->
<<Y:P,0:1>> = X,
Y.
when compiling the commented out version of test/2 i get a complaint that "variable 'P' is unbound".
Is there any good reason for not allowing the first version to work the same as the second?
Because in the commented out version P is a length - for it to work Erlang would need to perform a double match - match the value of the 2nd parameter with a pattern which is undetermined...
The question you are asking in a clause pattern match is "is this the clause for me" - you can't 'pop into the clause' and then back out if it isn't...
In the second example X is bound before the match, you are committed to going into the clause and if <<Y:P,0:1>> don't match X, well crash time!
The reason is that arguments to the function are evaluated independent of each other. The correctness of bindings to variables in only checked as a second step.
This means that in your first example P will be unbound when evaluating the second argument, which is against the rules of pattern matching. In contrast, in your second example, P is bound at the time of evaluating the pattern match on the binary.

Resources