F#:如何使用过滤谓词计算子集?

F#: how to calculate a subset using filtering predicate?

例如 对于 1 到 10 之间的整数,select 3 个数字:

1. Sum of these 3 numbers equals to 24
2. These 3 numbers could build a right triangle.

如何使用 F# 获取这 3 个数字? 我知道 Haskell 这很简单:

Prelude> let rightTriangle=[(a,b,c)|c<-[1..10],a<-[1..c],b<-[1..a],a^2+b^2==c^2,a+b+c==24]
Prelude> rightTriangle

解决方法是

[(8,6,10)]

我不确定

F# could help to generate a Cartesian product conveniently?
F# could add different filter conditions inside one expression?

那么,如何方便的用F#实现呢? 谢谢

F# 中 Haskell 版本的直接等价物是使用列表理解:

let rightTriangle=
  [for c in 1 .. 10 do
   for a in 1 .. c do
   for b in 1 .. a do
     if pown a 2 + pown b 2 = pown c 2 && a + b + c = 24 then
       yield a, b, c ]

一般来说,F# comprehensions 更接近 "normal F# language" 而不是一种特殊的语言功能(如果你去掉它周围的 [ .. ],它看起来几乎像命令式使用循环迭代)。

  • for构造对应a <- 1 .. 10,但要绑定多个变量需要嵌套多个for
  • if 构造对应于使用 Haskell
  • 中的 == 位进行过滤
  • yield 指定应从列表理解中返回哪些值