Difference between revisions of "User talk:Elias"

From HaskellWiki
Jump to navigation Jump to search
m
m
 
Line 21: Line 21:
   
 
Now <hask>hofun</hask> is a higher order function obtained by the parameterization of <hask>readln</hask>, it generalizes its behaviour.
 
Now <hask>hofun</hask> is a higher order function obtained by the parameterization of <hask>readln</hask>, it generalizes its behaviour.
The new function <hask>readln'</hask> calls <hask>foldm'</hask> with the original parameters. It can be checked by replacing the parameters in the body of the function.
+
The new function <hask>readln'</hask> calls <hask>hofun</hask> with the original parameters. It can be checked by replacing the parameters in the body of the function.
   
 
<haskell>
 
<haskell>

Latest revision as of 16:29, 3 January 2010

Exercises for the enthusiast beginner

A simple exercise, read carefully

This is a definition for the readln function. If you do not know the bind operator (>>=) yet, do not worry about it. p >> q behaves in a way similar to q(p), but it involves side effects. Anyway the error you are asked to find is not related with it.

> readln = h
>    where h = getChar >>= f 
>            where f c = case c of
>                          '\n'      -> return []
>                          otherwise -> h >>= (return . (:) c)

try

Main> readln >>= print

It works, as expected.

Now hofun is a higher order function obtained by the parameterization of readln, it generalizes its behaviour. The new function readln' calls hofun with the original parameters. It can be checked by replacing the parameters in the body of the function.

> readln' = hofun getChar '\n' (:) []

> hofun r s op e = h 
>    where h = r >>= f 
>            where f c = case c of
>                          s -> return e
>                          otherwise -> h >>= (return . op c)

try

Main> readln' >>= print

But readln' >>= print does not works printing the input line as readln >>= print does, there is an error, easy to find for the experienced eye. Can you discover it?