[erlang-questions] Tried this... Thought it interesting... But it didn't work.

zxq9 <>
Tue Sep 1 18:43:31 CEST 2015


On 2015年9月1日 火曜日 11:30:31  wrote:
> So, I ran across this tidbit in the Erlang cybersphere:
> 
> List Comprehension without generators
> 
> http://blog.equanimity.nl/blog/2015/03/15/erlang-one-weird-trick-goodiebag/
> 
> 1> Y = 3.
> 3
> 2> Z = [X || Y > 2].
> * 1: variable 'X' is unbound
> 
> OK.So I tried...
> 
> -module(test).
> 
> -compile(export_all).
> 
> test(Y) ->
>   [ X || Y > 2].
> 
> >3 test:test().
> Error: variable 'X' is unbound
> 
> Waah...is someone pulling my leg?
> 
> This worked...
> 
> 4> Z = [X || X <- [Y >2]].
> 
> But it seems rather pointless.

Hi there, Lloyd!

This is a shortcut. It is just using the test in the list comprehension to determine whether a list of one element or an empty list is returned. Both X and Y must already be defined in the scope of the expression:

1> X = 1.
1
2> Y = 2.
2
3> Z = [X || Y > 2].
[]
4> Q = [X || Y > 1].
[1]

Honestly, I don't really think this is the best use of list comprehension syntax. I can easily imagine people being confused at that, or at least requiring a few moments thought to figure out wtf is going on in that line. The fact this confounded you (and the example was unclear in the blog post, imo) is a good reason why you shouldn't do this in your code.

-Craig


More information about the erlang-questions mailing list