User talk:Elias
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 hofun
is a higher order function obtained by the parameterization of readln
, it generalizes its behaviour.
The new function readln'
calls foldm'
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?