News for hackers. Stuff that matters.
Re:How do I modify a variable in Haskell? by jamesbrock on Tuesday August 15, 2017 @11:28AM (#15019125)
Mr. Burge has written a nicely thought-out blog post showing an evolution of different ideas about how to write to an array in Haskell.

I don't want people trying to follow the evolution to get the impression that iterating and writing to an array is really hard in Haskell, so here is a complete Haskell program which

1. Initializes a 10x10 mutable array to 0.

2. Iterates in a for-loop from 0 to 9, setting the diagonal to 1.

3. Freezes the mutable array to an immutable array and prints it.

  module Main where
  
  import Foreign.C.Types (CInt)
  import Control.Monad (forM_)
  import Numeric.LinearAlgebra (toLists) -- http://hackage.haskell.org/package/hmatrix-0.18.1.0/docs/Numeric-LinearAlgebra-Data.html
  import Numeric.LinearAlgebra.Devel (runSTMatrix, newMatrix, writeMatrix) -- http://hackage.haskell.org/package/hmatrix-0.18.1.0/docs/Numeric-LinearAlgebra-Devel.html
  
  main = do
      putStrLn $ unlines $ fmap unwords $ fmap (fmap show) $ toLists aImmutable
    where
      aImmutable = runSTMatrix $ do
          a <- newMatrix (0::CInt) 10 10
          forM_ [0..9] $ \i -> writeMatrix a i i 1
          return a
Output:

  1 0 0 0 0 0 0 0 0 0
  0 1 0 0 0 0 0 0 0 0
  0 0 1 0 0 0 0 0 0 0
  0 0 0 1 0 0 0 0 0 0
  0 0 0 0 1 0 0 0 0 0
  0 0 0 0 0 1 0 0 0 0
  0 0 0 0 0 0 1 0 0 0
  0 0 0 0 0 0 0 1 0 0
  0 0 0 0 0 0 0 0 1 0
  0 0 0 0 0 0 0 0 0 1

There are no comments on this comment yet.