Reputation:
I'm a new programmer and using Haskell. I've found a line of code called find that matches up a String with its corresponding pair in a list. Like so
find a b = [x|(y,x) <- b, a==y]
I don't understand fully what this program is saying, for the list comprehension, as I've never seen the x|(y,x)
used in such a way before, I've mainly seen it used as x|x
or x|x^2
. So, does this mean that find the string A
, from your input list B
= a list comprehension of x
, where x
is a pair of (String, Char)
from your B
, and for which the y
equals your inputted a
? A little confused here.
Upvotes: 2
Views: 171
Reputation: 1047
Lets give you an example in order to visualize it:
find a b = [x|(y,x) <- b, a==y]
Let a=2
, b=[(1,3),(2,4),(3,5),(2,7)]
(y,x)
will get each of (1,3),(2,4),(3,5),(2,7)
as a couple and check if the first element equals 2
(we said that a
equals 2
). If True, the function will return the second element of that couple - x
, and put it in a list with the rest of the answers.
So the output for that function would be [4,7]
Upvotes: 2
Reputation: 62818
You seem to view "x|x
" as a thing. Rather, list comprehensions work like this:
[
expression to return|
stuff to iterate over]
What your example basically says is "draw (x, y)
from b
, throw away anything which doesn't satisfy a == y
, and then return x
".
Upvotes: 3
Reputation: 48581
I would pronounce that comprehension
The list of all
x
such that(y, x)
is drawn fromb
anda == y
.
Another way to read it, more sequentially:
Draw pairs
(y, x)
fromb
. For each such pair, check whethera == y
. If so, producex
; otherwise, move on to the next one.
I should also note that the variable names are a bit confusing. It's idiomatic in Haskell to give lists or other containers plural names. So something more like
find a abs = [x | (y, x) <- abs, a == y]
Upvotes: 7