[Haskell-beginners] IO ( stuff )

Antoine Latter aslatter at gmail.com
Fri Dec 9 21:11:50 CET 2011


On Fri, Dec 9, 2011 at 2:00 PM, Paul Monday <paul.monday at parsci.com> wrote:
> I've hammered through the bulk of my issues as I try to build a matrix that consists of random numbers, but the final hurdle is mixing pure and impure functions.  Does "impurity" from something like a random number generator or file I/O have to move it's way all the way through my code?
>
> Here is the specific example.  I have a function that makes a row in a matrix, it looks like this:
> makerow :: Int -> (Float, Float) -> IO (U.Vector Float)
>
> The IO (U.Vector Float) is the result of the random number generation that is an impure call, making this an impure result.
>
> I want to compose this into a list
> makerows :: Int -> Int -> (Float, Float) -> [U.Vector Float]
> makerows 0 _ _ = []
> makerows r n range = makerow n range : makerows r' n range
>    where r' = r - 1
>

The lifting operator you're looking for is the 'return' function.

A direct fix for your code given above would be:

makerows 0 _ _ = return []
makerows r n range = do
      x <- makerow n range
      xs <-  makerows r' n range
      return (x:xs)

If you understand why that works, you now understand Haskell IO.
Congratulations!

Even better, though, is:

makerows r n range = replicateM r (makerow n range)

See: http://hackage.haskell.org/packages/archive/base/latest/doc/html/Control-Monad.html#v:replicateM

Antoine



More information about the Beginners mailing list