簡體   English   中英

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

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

背景

我們正在F#中實現此算法。

在此處輸入圖片說明

Topor(1982)提供了有關該算法使用的符號的更多信息:

形式上, 't listnull (表示為nil )或具有hd (為't )和tl (為't list )...如果x為列表,則我們測試其是否為null通過寫null x ...我們創建一個新列表,將元素a添加到現有列表x的前面,方法是編寫a:x ...我們用list(a)表示包含元素a的單元列表。 list(x) = x:nil

我們想知道的是在F#中如何表達那些nilnulllist(nil)值。 例如,我們應該使用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 

處理列表時,對於list(nil)我們使用[[]] ,對於nil我們使用[] 沒關系,但是可能會有一種更具表現力的方式來做到這一點。 有時候,當類型推斷需要更多信息時,我們使用List.empty<'t list>List.empty<'t>

本文為您提供了所有答案: nil[] null xx是否為空列表的檢驗; list(nil)[[]]

算法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