简体   繁体   English

表示一个nil列表和/或一个列表(nil)

[英]Represent a nil list and/or a list(nil)

Background 背景

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 either null (denoted nil ) or has a hd (which is a 't ) and a tl (which is a 't list )... If x is a list, we test whether it is null by writing null x ... We create a new list, adding the element a at the front of an existing list x , by writing a:x ... We denote the unit list containing the element a by list(a) ... list(x) = x:nil . 形式上, 't listnull (表示为nil )或具有hd (为't )和tl (为't list )...如果x为列表,则我们测试其是否为null通过写null x ...我们创建一个新列表,将元素a添加到现有列表x的前面,方法是编写a:x ...我们用list(a)表示包含元素a的单元列表。 list(x) = x:nil

Question

What we're wondering is how in F# to express those nil , null , and list(nil) values. 我们想知道的是在F#中如何表达那些nilnulllist(nil)值。 For instance, should we be using the Option type, an empty list, or something else? 例如,我们应该使用Option类型,空列表还是其他?

What We Have Tried 我们尝试过的

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 xx是否为空列表的检验; 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM