2013-04-11 65 views
4

我習慣了用迭代器(F#:序列)做功能性事物的Python's itertools,並想知道F#或常用庫中是否有等價物,因爲它們非常方便。F的Itertools#

對我來說,頂部工具有:

  • 產物:笛卡兒積,相當於一個嵌套for循環
  • 組合
  • 排列
  • takewhile
  • dropwhile
  • 鏈:將多個迭代器連成一個新的更長的迭代器
  • 重複*:重複(5) - > 5,5,5 ...
  • count *:count(10) - > 10,11,12 ...
  • cycle *:cycle([1,2 ,3]) - > 1,2,3,1,2 ...

*我想這3個會在F#中產生單子嗎?你如何讓他們無限?

系統提示我問,因爲我看到了this question on permutations in F#,並且很驚訝它不是圖書館的一部分或者構建在語言中。

+0

'TakeWhile','dropwhile'鏈接和重複都包含在默認的F#庫中。 –

回答

4

我不知道是否有包含同類產品,組合和排列功能的常用庫,但你提到的其他人已經在SeqList模塊或可沒有太多的麻煩來實現,並有在System.Linq.Enumerable中也是有用的方法。

  • takewhile - >Seq.takeWhile
  • dropwhile - >Seq.skipWhile
  • chain - >Seq.concat
  • repeat - >Seq.initInfinite
  • count(10) - >Seq.initInfinite ((+) 10)
  • cycle([1, 2, 3]) - >Seq.concat <| Seq.initInfinite (fun _ -> [1; 2; 3])

你也可能想看看優秀的FSharpx庫 - 它包含許多有用的函數來處理集合和whatnot。