User talk:Elias

From HaskellWiki
Revision as of 16:29, 3 January 2010 by Elias (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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?