= Some [1] 我想将它转换成一个 List。 有公-6ren">
gpt4 book ai didi

functional-programming - 颠倒仿函数顺序的一般方法(一个可折叠的)

转载 作者:行者123 更新时间:2023-12-04 13:08:02 25 4
gpt4 key购买 nike

假设我有类似的东西

#r @"nuget: FSharpPlus"

open FSharpPlus

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

我想将它转换成一个 List

有公式化的机制吗?

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)

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

最佳答案

每当你有一堆 Functor,并且外部 FunctorTraversable 时,遍历 会翻转命令。您可以使用 sequence 简单地翻转两者:

let there = sequence maybeXs

这会产生 [Some 1]

关于functional-programming - 颠倒仿函数顺序的一般方法(一个可折叠的),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68489354/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com