1

I have a fragment of code from the Get Programming with Haskell book which looks as follows:

listToSTUArray :: [Int] -> ST s (STUArray s Int Int)
listToSTUArray vals = do
    let end =  length vals - 1
    myArray <- newArray (0,end) 0
    forM_ [0 .. end] $ \i -> do
      let val = vals !! i
      writeArray myArray i val
    return myArray

In order to better understand the full process of transformations inside the ST s context here I decided to expand these lines of code into the expression using >>, >>= and return. So my attempt results in this code:

listToSTUArray vals = (\end -> (newArray (0,end) 0) (length vals - 1)) >>= 
                      (\myArray -> (forM_ [...] >> return myArray))

Is it the correct expansion? And what is the general recipe to expand do-notations with forM_ or similar actions since they do some computations but throws away the result in a context?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
A. G
  • 187
  • 7
  • This can't be correct, because you have thrown away the entire body of `forM_`! – amalloy Oct 17 '21 at 20:51
  • 1
    @amalloy, forgot to mention explicitly that those square brackets meant the body of the ```forM_``` function, but since it just throws everything away I decided to consider only the outer part. – A. G Oct 17 '21 at 21:03
  • 2
    I think you have one paren wrong, it should be `(\end -> newArray (0,end) 0) (length vals - 1)`, but even that is not correct, because the `end` variable is also used in the `forM_`. You should probably just use a `let ... in ...` expression here: `let end = length vals - 1 in newArray (0, end) 0 >>= ...` – Noughtmare Oct 17 '21 at 21:06
  • 2
    Two minor points. 1) Lambdas span as to the right as possible: write `(\x -> ...)`, not `\x -> (...)`. 2) I hope that code in the book is only a first attempt which is improved later on, or some example of how you should not work with lists. Using `forM_ [0..n] $ \i ->` and then `vals !! i` is inefficient, and one should use something like `forM_ (zip vals [0..]) $ \(val,i) -> writeArray myArray i val`. – chi Oct 17 '21 at 21:18
  • see [this](https://stackoverflow.com/revisions/69608403/3). – Will Ness Oct 18 '21 at 12:40

0 Answers0