fib = f n 0 1

f 0 a b = a

f n a b = f (n-1) b (a+b)

This post was aimed at pythonistas, and people that claim that haskell is a single paradigm language that is unfriendly to people that only have experience in imperative programming.

]]>> fib n = flip evalState (0,1) $ do

> replicateM n $ modify (\(a,b) -> (b,a+b))

> gets fst

It’s good to see code expressed similarly between languages, but it makes me wonder if there’s another perhaps more expressive way to do the same in Python too!

]]>How about

modify \x -> (snd x, (snd x) + (fst x))

instead of “get” then “put”

for your state update.

And you can do “return $ gets fst” rather than getting b again and not using it. :-)

I actually wonder what the point-free version of that modify lambda expression would look like.

]]>fib :: Integer -> Integer

fib n = flip evalState (0,1) $ do

replicateM n $ do

modify $ \(a,b) -> (b,a+b)

gets fst

fib n =

let

fib 0 a b = a

fib n a b = fib $ n – 1 $ b $ a + b

in fib n 0 1

(a,b) <- get

put (b, a+b)

you could also do

modify (snd &&& uncurry (+))

Although whether that is clearer is up for debate. =)

]]>