haskell - Finding a single element in a list using list comprehension -
the function valueof
gets int
value of corresponding string
out of tuple list. can explain how third line works?
type state = [(string,int)] valueof :: state -> string -> int valueof xs var = head [b | (a,b) <- xs , ==var ]
i've never seen haskell expression that, i'm more used expression this:
(\xs -> length xs > 15)
there no lambda expression. seeing list comprehension, way of creating list of values satisfying condition.
in case comprehension [b | (a,b) <- xs , ==var ]
means like: create list of b
s such (a, b)
element of list xs
, a
equal var
.
in imperative pseudo-code write as
result = empty_list (a,b) in xs: if == var: result.add(b) return result
so, whole valueof
function works generating list of values have right string
key, , uses head
function first one. note if there no match, whole computation crash.
Comments
Post a Comment