If you make f
strict as in
f x = let y = x+1 in y `seq` Just y
or
-- remember to enable -XBangPatterns
f !x = Just (x+1)
and leave the rest alone, your code runs in constant space (albeit slowly) even with very large n
:
ghci> times 4000000000 f 3
Just 4000000003