如何将混合'T和seq 的输入展平为单个seq (How to flatten input of mixed 'T and seq into single seq)

编程入门 行业动态 更新时间:2024-10-28 02:32:33
如何将混合'T和seq <'T>的输入展平为单个seq <'T>(How to flatten input of mixed 'T and seq<'T> into single seq<'T>)

我需要一个可以接受任意数量参数的函数,每个参数可以是'T或seq<'T> 。 在函数内部,我需要将其作为单个seq<'T> ,所有输入的组合顺序与它们提供的顺序相同。

显而易见的方法是:

module Test = let flatten ([<ParamArray>] args) = let flat = seq { for a in args do match box a with | :? int as x -> yield x | :? seq<int> as sq -> for s in sq do yield s | _ -> failwith "wrong input type" } flat // this should be seq<int>

但即使是最简单的情况,我也无法在FSI中发挥作用

let fl = Test.flatten 1;; ----------------------^ ...: error FS0001: The type 'int' is not compatible with the type 'seq<'a>'

这里有什么问题以及如何根据需要使其工作? 可能这可以用一些完全不同的方式完成吗?

I need a function that could take an arbitrary number of arguments, each could be either of type 'T or seq<'T>. Inside the function I need to process it as a single seq<'T> with all inputs combined in the same order as they sere supplied.

The obvious way was to have something like:

module Test = let flatten ([<ParamArray>] args) = let flat = seq { for a in args do match box a with | :? int as x -> yield x | :? seq<int> as sq -> for s in sq do yield s | _ -> failwith "wrong input type" } flat // this should be seq<int>

but I cannot make it work in FSI even with the simplest case

let fl = Test.flatten 1;; ----------------------^ ...: error FS0001: The type 'int' is not compatible with the type 'seq<'a>'

What is wrong here and how to get it work as needed? Probably this could be done in some completely different way?

最满意答案

来自msdn :

在F#中,参数数组只能在方法中定义。 它们不能用于模块中定义的独立功能或功能。

因此,使用静态方法声明类型而不是模块。

open System type Test() = static member flatten ([<ParamArray>] args: obj[]) = let flat = seq { for a in args do match box a with | :? int as x -> yield x | :? seq<int> as sq -> for s in sq do yield s | _ -> failwith "wrong input type" } flat

如果您有其他let绑定,您仍然可以声明具有相同名称的模块。 另请注意,在比赛的第二个后卫中,您可以通过执行以下操作来避免for循环:

| :? seq<int> as sq -> yield! sq

并且不需要box 。

From msdn :

In F#, parameter arrays can only be defined in methods. They cannot be used in standalone functions or functions that are defined in modules.

So instead of a module, declare a type with a static method.

open System type Test() = static member flatten ([<ParamArray>] args: obj[]) = let flat = seq { for a in args do match box a with | :? int as x -> yield x | :? seq<int> as sq -> for s in sq do yield s | _ -> failwith "wrong input type" } flat

If you have other let bindings you can still declare a module with the same name. Also note that in the second guard of the match you can avoid the for loop by doing:

| :? seq<int> as sq -> yield! sq

And box is not required.

更多推荐

本文发布于:2023-08-03 18:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将   seq   flatten   single   mixed

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!