簡體   English   中英

Ocaml:元組列表上的遞歸

[英]Ocaml: recursion on a list of tuples

我有下面的函數表,其中包含一個元組列表(x是字符串,y是字符串列表),我想返回一個元組x1和列表y1的長度。 我用這個簡單的功能試了一下:

let rec table lst = function
    | [] -> []
    | [(x1, y1, x2, y2)] -> [(x1, (List.length y1))]
    | (x1_h, y1_h, x2_h, y2_h) :: tail -> (x1_h, (List.length y1_h))::(table tail)

但是發生了以下錯誤:

錯誤:此表達式的類型為('a *'b list *'c *'d)list->('a * int)list,但是期望表達式為('a * int)list類型

我不確定自己在哪里做錯了。

function隱式地接受參數,並在其上進行模式匹配。 換一種說法:

let f = function | ...

相當於

let f lst = match lst with | ...

所以當你寫

let rec table lst = function | ...

轉化為

let rec table lst lst2 = match lst2 with | ...

錯誤指向遞歸調用table tail ,因為它被部分應用並返回一個函數('a * 'b list * 'c * 'd) list -> ('a * int) table tail tail將按預期方式返回('a * int list) ,並且完全有效。 但是由於lst在您的函數中未使用,因此您可以刪除它。

暫無
暫無

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

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