簡體   English   中英

F#-遞歸列表

[英]F# - Recursion on list

輸入:[x1; x2; ...; xn]

輸出([x1; x3; ...; xn],[x2; x4; ...; xn],[x3; x5; ...; xn],....)

到目前為止,我有:

let rec split = function
| x0 :: x1 :: xs -> (x0::xs) :: split(x1::xs)
| _ -> []

產生:

Input: [1;2;3;4;5;6]
Output: [[1; 3; 4; 5; 6]; [2; 4; 5; 6]; [3; 5; 6]; [4; 6]; [5]]

我不太清楚如何遞歸地建立一個列表元組。

有任何想法嗎?

我不知道您為什么要這樣做,如果我不想給您答案,但是我想給您一個提示,最好從做某件事的方式開始,正確的方向。

此代碼獲取一個列表,並且以非常不必要的復雜方式進行遞歸,返回其中三個的元組。

let rec tripleList : List<'a> -> (List<'a> * List<'a> * List<'a>) = 
    function 
    | []    -> ([],[],[])
    | (x :: xs) -> 
        let (tail1,tail2,tail3) = tripleList xs
        (x :: tail1,x :: tail2,x :: tail3)

> tripleList [1..10];;
val it : List<int> * List<int> * List<int> =
  ([1; 2; 3; 4; 5; 6; 7; 8; 9; 10], [1; 2; 3; 4; 5; 6; 7; 8; 9; 10],
   [1; 2; 3; 4; 5; 6; 7; 8; 9; 10])

您也不需要將整個功能作為一個函數來完成,您可以創建3個函數,其中1個構建元組的每個部分,然后創建第四個函數,調用這3個函數來組合答案。 那可能是一個更簡單的起點。

所以類似的事情將會是...

let rec tripleList1 : List<'a> -> List<'a> = 
    function 
    | []    -> []
    | (x :: xs) -> 
        (x :: tripleList1 xs)

let rec tripleList2 : List<'a> -> List<'a> = 
    function 
    | []    -> []
    | (x :: xs) -> 
        (2 * x :: tripleList2 xs)

let rec tripleList3 : List<'a> -> List<'a> = 
    function 
    | []    -> []
    | (x :: xs) -> 
        (3 * x :: tripleList3 xs)


let tripleList : List<int> -> (List<int> * List<int> * List<int>) = 
    fun xs -> 
        (tripleList1 xs,tripleList2 xs,tripleList3 xs)

我更喜歡第一種方法,但是兩者都是完全有效的,並且區分了創建遞歸數據結構List <'a>所需的遞歸函數,而元組只需要一個簡單的獨立函數

因此,也許嘗試編寫一個需要的函數。

[1,2,3,4,5,6,7]-> [1,3,5,7]

然后查看是否可以將其概括化,然后將其組裝到另一個函數中

(請注意,不要被我的示例所誤導,它們具有正確的結構,但它們根本無法滿足您的需要,您需要以某種方式過濾掉值)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM