Difference between revisions of "User talk:Elias"

From HaskellWiki
Jump to navigation Jump to search
m (I started my page with this example)
 
m
 
(One intermediate revision by the same user not shown)
Line 20: Line 20:
 
It works, as expected.
 
It works, as expected.
   
  +
Now <hask>hofun</hask> is a higher order function obtained by the parameterization of <hask>readln</hask>, it generalizes its behaviour.
Now foldm' is a readln parametrized, the new function readln' calls foldm' with the original parameters.
 
  +
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>
> readln' = foldm' getChar '\n' (:) []
+
> readln' = hofun getChar '\n' (:) []
   
> foldm' r s op e = h
+
> hofun r s op e = h
 
> where h = r >>= f
 
> where h = r >>= f
 
> where f c = case c of
 
> where f c = case c of
Line 37: Line 38:
 
</haskell>
 
</haskell>
   
But <hask>readln' >>= print</hask> does not works printing the input line as <hask>readln >>= print</hask> does, there is an error, easy to find for the experienced programmer, Can you discover it?
+
But <hask>readln' >>= print</hask> does not works printing the input line as <hask>readln >>= print</hask> does, there is an error, easy to find for the experienced eye. Can you discover it?

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?