User talk:Elias

From HaskellWiki
Revision as of 11:35, 3 January 2010 by Elias (talk | contribs) (I started my page with this example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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 foldm' is a readln parametrized, the new function readln' calls foldm' with the original parameters.

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

> foldm' 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 programmer, Can you discover it?