[英]Represent a nil list and/or a list(nil)
We are implementing this algorithm in F#. 我们正在F#中实现此算法。
Here is a little bit more information from Topor (1982) about the notation that the algorithm uses: Topor(1982)提供了有关该算法使用的符号的更多信息:
Formally, a
't list
is eithernull
(denotednil
) or has ahd
(which is a't
) and atl
(which is a't list
)... Ifx
is a list, we test whether it isnull
by writingnull x
... We create a new list, adding the elementa
at the front of an existing listx
, by writinga:x
... We denote the unit list containing the elementa
bylist(a)
...list(x) = x:nil
. 形式上,'t list
为null
(表示为nil
)或具有hd
(为't
)和tl
(为't list
)...如果x
为列表,则我们测试其是否为null
通过写null x
...我们创建一个新列表,将元素a
添加到现有列表x
的前面,方法是编写a:x
...我们用list(a)
表示包含元素a
的单元列表。list(x) = x:nil
。
What we're wondering is how in F# to express those nil
, null
, and list(nil)
values. 我们想知道的是在F#中如何表达那些nil
, null
和list(nil)
值。 For instance, should we be using the Option type, an empty list, or something else? 例如,我们应该使用Option类型,空列表还是其他?
let rec kpermute k (xs: 't list) =
let rec mapPerm k xs ys =
match ys with
| [] -> []
| head::tail ->
let kpermuteNext = kpermute (k-1) (removeFirst head xs)
let mapPermNext = mapPerm k xs tail
mapcons head kpermuteNext mapPermNext
match k with
| 0 -> [[]]
| _ when xs.Length < k -> []
| _ -> mapPerm k xs xs
When working with lists, for list(nil)
we use [[]]
and for nil
we use []
. 处理列表时,对于list(nil)
我们使用[[]]
,对于nil
我们使用[]
。 While that's fine, there might be a more expressive way to do it. 没关系,但是可能会有一种更具表现力的方式来做到这一点。 There are also times when we use List.empty<'t list>
and List.empty<'t>
when the type inference needs more information. 有时候,当类型推断需要更多信息时,我们使用List.empty<'t list>
和List.empty<'t>
。
The paper gives you all the answers: nil
is []
; 本文为您提供了所有答案: nil
为[]
; null x
is a test for whether x
is the empty list; null x
是x
是否为空列表的检验; list(nil)
is [[]]
. list(nil)
是[[]]
。
The naïve translation of algorithm B to F# is as follows: 算法B到F#的简单转换如下:
let rec minus a = function
| [] -> failwith "empty list"
| xh :: xt -> if xh = a then xt else xh :: minus a xt
let rec permute2 k x =
if k = 0 then [[]]
elif List.length x < k then []
else mapperm k x x
and mapperm k x = function
| [] -> []
| yh :: yt -> mapcons yh (permute2 (minus yh x)) (mapperm x yt)
and mapcons a ps qs =
match ps with
| [] -> qs
| ph :: pt -> a :: ph :: mapcons a pt qs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.