[erlang-questions] list comprehensions with predefined functions?
Richard A. O'Keefe
ok@REDACTED
Thu Jun 19 01:07:38 CEST 2008
On 19 Jun 2008, at 12:08 am, Circular Function wrote:
> how do i use a predefined function in a list comprehension?
The same way you use it anywhere else.
>
>
> and if i have 2 variables how do I write then?
The same way you write them anywhere else.
>
>
>
> 42> c(mymath).
> {ok,mymath}
> 43> [mymath:power || X <- [1,2,3] Y <- 3].
> * 1: syntax error before: Y
You are missing a comma exactly where the error message
tells you it is in trouble.
[...... || X <- [1,2,3], Y <- 3].
Y <- 3 is pretty meaningless; a "generator" using <-
expects to generate the elements of a LIST, and 3 is not
a list. So
[...... || X <- [1,2,3], Y <- [3]].
>
> 43> [mymath:power || X <- [1,2,3], Y <- 3].
> * 1: illegal expression
Where are the arguments of your function?
[mymath:power(X, Y) || X <- [1,2,3], Y <- [3]].
>
> 44> [mymath:cube || X <- [1,2,3]].
> * 1: illegal expression
> 45> [X*2 || X <- [1,2,3]].
This should have given you a clue: the thing between
the "[" and the "||" is a perfectly ordinary expression
where all the normal rules about expressions apply.
The only difference is that the variables bound by the
generators may be used in this expression.
>
> [2,4,6]
> 46> [X*X || X <- [1,2,3]].
> [1,4,9]
> 47> [X*2 || X <- [1,2,3]].
> [2,4,6]
> 48> [mymath:sq || X <- [1,2,3]].
> * 1: illegal expression
Once again: where is the argument of mymath:sq?
<module>:<name> is NEVER meaningful in Erlang.
If you want to refer to a function, you always
need to specify its arity, and in any case, the
expression here should be a normal expression.
By the way, there is nothing unusual about Erlang here.
All the languages I know that have list/array/set/tuple/...
comprehensions do exactly the same thing:
<opening bracket>
<normal expression>
<separator>
<generators and maybe guards>
<closing bracket>
More information about the erlang-questions
mailing list