Home > Uncategorized > Some code kata – haskell for loops

Some code kata – haskell for loops

First of all – read and enjoy solving these small puzzle problems.

I also did that but with a little twist – I picked haskell which makes the first problem a bit more challenging. Why? Because for and while loops requires mutable states which is something that is not supported by haskell. Unless… you turn to monads and more specifically the state monad.

Lets repeat problem 1:

Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.

In the standard library Control.Monad we can actually find primitives for for-loops. The one that I used is called forM_ and has the type signature

forM_ :: (Foldable t, Monad m) => t a -> (a -> m b) -> m ()

The first argument is a foldable type t which is similiar to enumerable in .net. It is generic so any item of type a might be enumerated.

The second argument is the action that we want to repeatadly invoke. It takes as an argument an element of the enumerable. It returns a monad containing a value of some type b. Do not worry too much about what a monad is right now just hang on.

The result is a monad without a value (or for purists: the only value of the unit type). This indicates that the result of the forM_ function is only side effects. Side effects within the monad that is.

The standard monad for side effects is the State monad. To execute a state monad and actually get a result the following function is provided

execState :: State s a -> s -> s

It takes a state monad and an initial state and returns the resulting state.

Last, but not least, we need to be able to modify the state.

modify :: MonadState s m => (s -> s) -> m ()

Using this function we can pass a function that takes the current state as input and returns the new state.

Putting the pieces together we get

import Control.Monad
import Control.Monad.State

sumUsingFor xs = execState loop 0
        loop = forM_ xs $ \x -> modify (+x)

I think that is pretty impressive for a language that does not support mutable states.

Next time, we will have a look at the while loop implementation.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: