The function valueOf gets the Int value of the corresponding String out of a tuple list.
Can someone explain how the third line works?
type State = [(String,Int)]
valueOf :: State -> String -> Int
valueOf xs var = head [b | (a,b) <- xs , a ==var ]
I've never seen a Haskell expression like that, I'm more used to expression like this:
(\xs -> length xs > 15)
There is no lambda expression. What you are seeing is a list comprehension, which is a way of creating a list of values satisfying a certain condition.
In this case the comprehension [b | (a,b) <- xs , a ==var ] means something like: create a list of all bs such that (a, b) is an element of list xs, where a is equal to var.
In imperative pseudo-code you could write it as
result = EMPTY_LIST
for (a,b) in xs:
if a == var:
result.add(b)
return result
So, the whole valueOf function works by generating a list of values that have the right String key, and then uses head function to get the first one. Note that if there is no match, the whole computation will crash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With