开发者

IEnumerable<T> in OCaml

开发者 https://www.devze.com 2023-03-17 07:00 出处:网络
I use F# a lot. All the basic collections in F# implement IEumberable interface, thus it is quite natural to access them using the single Seq module in F#. Is this possible in OCaml?

I use F# a lot. All the basic collections in F# implement IEumberable interface, thus it is quite natural to access them using the single Seq module in F#. Is this possible in OCaml?

The other question is that 'a seq in F# is lazy, e.g. I can create a sequence from 1 to 100 using {1..1开发者_如何学C00} or more verbosely:

seq { for i=1 to 100 do yield i }

In OCaml, I find myself using the following two methods to work around with this feature:

  1. generate a list:

    let rec range a b = 
      if a > b then []
      else a :: range (a+1) b;;
    
  2. or resort to explicit recursive functions.

The first generates extra lists. The second breaks the abstraction as I need to operate on the sequence level using higher order functions such as map and fold.

I know that the OCaml library has Stream module. But the functionality of it seems to be quite limited, not as general as 'a seq in F#.

BTW, I am playing Project Euler problems using OCaml recently. So there are quite a few sequences operations, that in an imperative language would be loops with a complex body.


This Ocaml library seems to offer what you are asking. I've not used it though.

http://batteries.forge.ocamlcore.org/

Checkout this module, Enum http://batteries.forge.ocamlcore.org/doc.preview:batteries-beta1/html/api/Enum.html

I somehow feel Enum is a much better name than Seq. It eliminates the lowercase/uppercase confusion on Seqs.


An enumerator, seen from a functional programming angle, is exactly a fold function. Where a class would implement an Enumerable interface in an object-oriented data structures library, a type comes with a fold function in a functional data structure library.

Stream is a slightly quirky imperative lazy list (imperative in that reading an element is destructive). CamlP5 comes with a functional lazy list library, Fstream. This already cited thread offers some alternatives.


It seems you are looking for something like Lazy lists. Check out this SO question


The Batteries library mentioned also provides the (--) operator:

# 1 -- 100;;
- : int BatEnum.t = <abstr>

The enum is not evaluated until you traverse the items, so it provides a feature similar to your second request. Just beware that Batteries' enums are mutable. Ideally, there would also be a lazy list implementation that all data structures could be converted to/from, but that work has not been done yet.

0

精彩评论

暂无评论...
验证码 换一张
取 消