Strecster
Strecster

Reputation: 75

Evaluate a list of computation expression values

What's a good way to evaluate a list of computation expression values into the corresponding list of values?

Let's say my computation expression type is M<a> then I'm wondering what is the best way to write the function:

mysequence : list<M<'a>> -> M<list<'a>>

I could write this out recursively:

let rec mysequence = function
    | [] -> builder { return [] }
    | (x::xs) -> builder { let! y = x
                           let! ys = mysequence xs
                           return (y::ys)
                         }

Is there a more concise way?

Upvotes: 2

Views: 75

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243041

You could make this a bit shorter by using List.fold and even shorter if you introduced a couple of helper combinators such as a lift2 function of the following type:

lift2 : ('a -> 'b -> 'c) -> M<'a> -> M<'b> -> M<'c>

This is something you can easily define using the builder { .. } notation and it lets you turn functions that work on normal values into functions that work on wrapped values. You could then lift the list consing operation and use that with fold. Doing that will make the code shorter (if you ignore all the helpers one has to write), but it also makes it pretty ugly and obscure.

If I was writing this, I'd go with something very close to your version. I prefer to keep the entire body in builder { .. } rather than having function and I'd also use the accumulator parameter, so I'd write:

let rec mysequence acc input = builder {
  match input with 
  | [] -> return List.rev acc
  | x::xs -> 
      let! y = x
      return! mysequence (y::acc) xs }

But aside from the accumulator and some minor syntactic differences, it's pretty much the same as yours!

Upvotes: 4

Related Questions