
Hi,
Hi. This sort of question belongs on haskell-café. I've copied this reply there.
I still have confusing regarding the following case:
elemNum2 :: Int -> [Int] -> Int elemNum2 elem list = sum [ 1 | findElem <- list, elem == findElem ]
the function I wrote finds the number of occurences of an element in a list. If I change it to the following:
elemNum2 elem list = sum [ 1 | elem <- list ]
Now it simply gives the length of the list. OK I understand that "elem" in the list comprehension defines a new variable on the fly. What I do not understand is in the first case:
"findElem <- list" findElem is a new variable, but "list" is not. "elem==findElem" here for some reason "elem" is not a new variable.
Why does the rule only apply for "<-" operation, but not "==" for example?
Thanks
<- and let ... = ... aren't operations, they're definitions. == is the usual comparison operator. A list comprehension includes both definitions and predicates -- expressions of type Bool, or if you prefer, "operations returning" Bool. Definitions are either "let <var> = <expr>", as in [a | let a = 1], which evaluates to [1], or <var> <- <expr> where expr:: [t] for some t. You can read <- as "drawn from" [a | a <- [1,2,3]] evaluates to [1,2,3], and if we add a predicate: [a | a <- [1,2,3], odd a] evaluates to [1,3] and [a | a <- [1,2,3], a == 1] evaluates to [1] Hope that helps Jón -- Jón Fairbairn Jon.Fairbairn@cl.cam.ac.uk 31 Chalmers Road jf@cl.cam.ac.uk Cambridge CB1 3SZ +44 1223 570179 (after 14:00 only, please!)
participants (1)
-
Jon Fairbairn