抽象集合类型 [英] Abstracting over Collection Types

查看:140
本文介绍了抽象集合类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能编写除了使用 seq 模块之外的其他支持的集合类型的通用函数?



目标是在添加新的集合函数时不必求助于复制和粘贴。

解决方案

code> seq<'T> 类型是编写适用于F#中任何集合的计算的主要方式。有几种方法可以处理类型:




  • 您可以使用 Seq 模块(例如 Seq.filter Seq.windowed 等)

  • 您可以使用顺序理解(例如 seq {for col in> x * 2}

  • 您可以使用底层的(命令式) IEnumerator<'T> 类型,有时需要如果你想实现你自己的集合拉链(这是通过调用 GetEnumerator )返回


$ b b

这是相对简单的类型,它只能用于从集合中读取数据。因此,您将始终获得类型 seq 的值,这本质上是一个延迟序列。



F#没有任何转换集合的机制(例如将集合 C 移至集合 C 新值)或任何创建集合的机制(在Haskell或Scala中可用)。



在大多数实际情况下,我没有发现问题 - 大多数工作可以使用 seq<'T> 来完成,当你需要一个专门的集合(例如性能数组)时,你通常需要一个稍微不同的实现。 / p>

Is there a possibility of writing functions which are generic in respect to collection types they support other than using the seq module?

The goal is, not having to resort to copy and paste when adding new collection functions.

解决方案

The seq<'T> type is the primary way of writing computations that work for any collections in F#. There are a few ways you can work with the type:

  • You can use functions from the Seq module (such as Seq.filter, Seq.windowed etc.)
  • You can use sequence comprehensions (e.g. seq { for x in col -> x * 2 })
  • You can use the underlying (imperative) IEnumerator<'T> type, which is sometimes needed e.g. if you want to implement your own zipping of collections (this is returned by calling GetEnumerator)

This is relatively simple type and it can be used only for reading data from collections. As the result, you'll always get a value of type seq<'T> which is essentially a lazy sequence.

F# doesn't have any mechanism for transforming collections (e.g. generic function taking collection C to collection C with new values) or any mechanism for creating collections (which is available in Haskell or Scala).

In most of the practical cases, I don't find that a problem - most of the work can be done using seq<'T> and when you need a specialized collection (e.g. array for performance), you typically need a slightly different implementation anyway.

这篇关于抽象集合类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆