Monday 15 June 2015

haskell - Mutually recursive IO definitions -



haskell - Mutually recursive IO definitions -

i can write following:

f :: [int] -> [int] f x = 0:(map (+1) x) g :: [int] -> [int] g x = map (*2) x = f b b = g main = print $ take 5

and things work fine (ideone).

however, lets want g more complex multiply 2, inquire user number , add together that, so:

g2 :: [int] -> io [int] g2 = mapm (\x -> getline >>= (return . (+x) . read))

how then, well, tie knot?

clarification:

basically want list of ints f input of g2 , list of ints g2 input of f.

the effectful generalization of lists listt:

import control.monad import pipes f :: listt io int -> listt io int f x = homecoming 0 `mplus` fmap (+ 1) x g2 :: listt io int -> listt io int g2 x = n <- x n' <- lift (fmap read getline) homecoming (n' + n) = f b b = g2 main = runlistt $ n <- lift (print n) mzero

you can implement take functionality little code:

import qualified pipes.prelude pipes take' :: monad m => int -> listt m -> listt m take' n l = select (enumerate l >-> pipes.take n) main = runlistt $ n <- take' 5 lift (print n) mzero

example session:

>>> main 0 1<enter> 2 2<enter> 3<enter> 7 4<enter> 5<enter> 6<enter> 18 7<enter> 8<enter> 9<enter> 10<enter> 38

you can larn more listt reading pipes tutorial, section on listt.

haskell

No comments:

Post a Comment