# free variable

**Jon Fairbairn
**
Jon.Fairbairn@cl.cam.ac.uk

*Thu, 09 Aug 2001 11:16:16 +0100*

>* Hi,
*
Hi. This sort of question belongs on haskell-caf=E9. I've
copied this reply there.
>* I still have confusing regarding the following case:
*>* =
*
>* elemNum2 :: Int -> [Int] -> Int
*>* elemNum2 elem list =3D sum [ 1 | findElem <- list, elem =3D=3D 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 =3D 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=3D=3DfindElem" here for some reason "elem" is not a new variable.=
*
>* =
*
>* Why does the rule only apply for "<-" operation, but not "=3D=3D" for e=
*xample?
>* =
*
>* Thanks
*
<- and let ... =3D ... aren't operations, they're
definitions. =3D=3D 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> =3D <expr>", as in
[a | let a =3D 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 =3D=3D 1] =
evaluates to [1]
Hope that helps
J=F3n
-- =
J=F3n Fairbairn Jon.Fairbairn@cl.cam.ac.u=
k
31 Chalmers Road jf@cl.cam.ac.uk
Cambridge CB1 3SZ +44 1223 570179 (after 14:00 only, please!)