High order function returning result and modified itself

My goal is to create function, which take argument, compute result and return it in tuple with modified itself.

My first try looked like this:

f x = (x,f') where
    f' y = (y+1,f') 

cl num func = let (nu,fu) = func num in nu:fu num

My desired result if I call function cl with 0 and f was

[0,1,2,3,4,5,6,7,8,9,10,11,12,13 ... infinity]

Unfortunately, haskell cannot construct infinite type. It is hard for me to devise another way of doing it. Maybe, I'm just looking at problem from the bad side, thats why I posted this question.

EDIT: This is the state of my functions:

newtype InFun = InFun { innf :: Int -> (Int,InFun) }

efunc x = (x,InFun deep) where
    deep y = (y+1, InFun deep)

crli n (InFun f) = let (n',f') = f n in n':crli n f'

main = putStrLn $ show (take 10 (crli 0 (InFun efunc)))

Result is [0,1,1,1,1,1,1,1,1,1]. That's better, But, I want the modification made by deep function recursive.


  • Probably you are looking for

    {-# LANGUAGE RankNTypes #-}
    newtype F = F { f :: Int -> (Int, F) }
    g y = (y + 1, F g)


    *Main> fst $ (f $ snd $ g 3) 4


    *Main> map fst $ take 10 $ iterate (\(x, F h) -> h x) (g 0)

    or more complex modification (currying)

    h = g False
        where g x y = (y', F g')
                      where y' = if x then y + 1
                                      else 2 * y
                            g' = if x then g False
                                      else g True


    *Main> map fst $ take 10 $ iterate (\(x, F h) -> h x) (h 0)