[Haskell-cafe] How to write fast for loops

Niklas Hambüchen mail at nh2.me
Sun Apr 27 01:46:07 UTC 2014


Thanks for the insight! There's one thing I don't understand yet:

On 27/04/14 02:32, Daniel Fischer wrote:
> The problem is that you use the same list multiple times, and GHC thinks "hey, 
> let me re-use that", so it gets floated to the top-level, and the inner "loop" 
> really uses the list, which apart from the `case`s on the list forces it to 
> use boxed 'Int's instead of Int#. Then the boxed Ints need to be unboxed to be 
> used, oops.

When you say that the problem is that I "use the same list multiple
times", do you mean that I use the actual syntactic expression
`[0.._SIZE-1]` multiple times on multiple lines, and suggest that this
should not happen if I use it in only one place?

If so, how far does that go, and would GHC even notice that it is the
same as a potential `[0.._511]` I might write elsewhere?

> Do the idiomatic thing and write a loop ;)

Unfortunately, `forM_ [1..n]` is pretty much the most idiomatic and
beautiful way I can come up with when ask for an iteration over 1 up to
n! So this better be fixed :)


More information about the Haskell-Cafe mailing list