functional-programming - 倒转 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)
一般来说,这是一个公平的方法吗?还是有一些功能性的神奇配方,可以带来一些清晰?
解决方案
每当您有一堆Functors
,而外部Functor
是Traversable
时,遍历就会翻转顺序。您可以使用sequence
简单地翻转两者:
let there = sequence maybeXs
这产生[Some 1]
.
推荐阅读
- c# - 排序列表
> 在 C# 中 - python - Google Drive API 找不到任何文件夹
- c# - 反序列化列表
从 fetch 调用时...C# - unity3d - 我们如何在 Unity3D 的实体组件系统中获得刚体行为?
- vb.net - 我可以为从我的程序启动的进程设置标识属性吗?
- nativescript - 运行 tns 资源生成图标杀死 iOS 应用程序
- angularjs - 如何修复此代码以在网页上显示内容?
- css - 如何居中一个很棒的图标和跨度
- java - 在 Android Studio 中找不到 getExternalFilesDir() 函数的上下文
- r - 如何将套索和岭回归拟合(Glmnet)叠加到数据上?