general recipe for reversing order of Functors (one foldable)

Viewed 54

lets say I have something like

#r @"nuget: FSharpPlus"

open FSharpPlus

let maybeXs: Option<List<int>> = Some [1]

and I want to transform it to a List<Option> out of it.

is there a formulaic mechanism?

let unit = Some

let almostThere: Option<List<Option<int>>> = map (fun xs -> map unit xs) maybeXs

I just need to 'eliminate' the outer option....which then seems to be specific to my data type so

let there: List<Option<int>> = 
    fold (fun s t -> t) [] (map (fun xs -> map unit xs) maybeXs)

is this a fair recipe to do this in general? or is there some functional magical recipe, that brings some clarity?

1 Answers

Whenever you have a stack of Functors, and the outer Functor is Traversable, a traversal flips the order. You can use sequence to simply flip the two:

let there = sequence maybeXs

This produces [Some 1].

Related