Flattening a mixture of lists and single elements in Haskell

Viewed 95

In F# I can use the yield/yield! syntax in order to concat a mixture of single elements and arrays into a single collection, e.g.

let result = seq {
    yield 1
    yield! [2;3;4;5]
    yield! [6;7]
    yield 8
}

printfn "%A" result
// Prints: seq [1; 2; 3; 4; ...]

I'm wondering if there's a similar way of doing this in Haskell.

1 Answers

The equivalent would be:

result = concat [
     [1],
     [2,3,4,5],
     [6,7],
     [8]
  ]

Your comment:

It would work, but I'd need to turn my single elements into lists first.

kinda misses the point. Your F# version is already turning single elements into lists. That's what yield does.

But if you're really hung up on the syntax, you can replicate it very closely with the writer monad:

import Control.Monad.Writer

yield x = tell [x]
yield' = tell

result = execWriter do
  yield 1
  yield' [2,3,4,5]
  yield' [6,7]
  yield 8
Related