Caml/Ocaml: 模式匹配多参数函数
Caml/Ocaml: pattern matching multiple argument functions
我正在尝试制作这个递归函数,它接受一个 int x
和一个列表,然后从列表中删除第一个 x
数量的元素:
let rec nthcdr int_t list_t =
match int_t with
| 0 -> list_t
| _ -> (match list_t with
| [] -> []
| h::tail -> nthcdr (int_t -1) tail)
;;
但它不起作用,h::tail
似乎永远不会匹配,它总是returns []
我想提供对代码的改进作为答案(因为 OP 已经找到了解决方案)。
模式匹配一个整数感觉多余int_t
。您当然可以这样做,但是当与代数数据类型(如记录或变体或列表等集合)一起使用时,模式匹配的好处会变得很明显。此外,对整数使用 if..else
可以使代码更清晰,并将基本情况与归纳情况区分开来。
let rec drop n li =
if n = 0 then li else
match li with
| [] -> []
| h::t -> drop (n-1) t
我正在尝试制作这个递归函数,它接受一个 int x
和一个列表,然后从列表中删除第一个 x
数量的元素:
let rec nthcdr int_t list_t =
match int_t with
| 0 -> list_t
| _ -> (match list_t with
| [] -> []
| h::tail -> nthcdr (int_t -1) tail)
;;
但它不起作用,h::tail
似乎永远不会匹配,它总是returns []
我想提供对代码的改进作为答案(因为 OP 已经找到了解决方案)。
模式匹配一个整数感觉多余int_t
。您当然可以这样做,但是当与代数数据类型(如记录或变体或列表等集合)一起使用时,模式匹配的好处会变得很明显。此外,对整数使用 if..else
可以使代码更清晰,并将基本情况与归纳情况区分开来。
let rec drop n li =
if n = 0 then li else
match li with
| [] -> []
| h::t -> drop (n-1) t