首页 > 解决方案 > 倒转 Functor 顺序的通用配方(一个可折叠)

问题描述

可以说我有类似的东西

#r @"nuget: FSharpPlus"

open FSharpPlus

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

我想将其转换为 List<Option> 。

有公式化的机制吗?

let unit = Some

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

我只需要“消除”外部选项....然后似乎特定于我的数据类型,所以

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

一般来说,这是一个公平的方法吗?还是有一些功能性的神奇配方,可以带来一些清晰?

标签: functional-programmingf#

解决方案


每当您有一堆Functors,而外部FunctorTraversable时,遍历就会翻转顺序。您可以使用sequence简单地翻转两者:

let there = sequence maybeXs

这产生[Some 1].


推荐阅读