Functional programming 如何在元组构造函数(OCaml)上进行模式匹配
我有以下几种:Functional programming 如何在元组构造函数(OCaml)上进行模式匹配,functional-programming,pattern-matching,ocaml,Functional Programming,Pattern Matching,Ocaml,我有以下几种: type letter = A | B | C | D (*...*) type mix = Char of letter | Mix of (mix * int) list 我想做一个函数,它计算组合中字母的出现次数,但很难正确匹配模式 let rec count_char letter mix = match mix with | Char l -> (*...*) | Mix (m, i) -> (*...*) 我得到了这个错误 Error:
type letter = A | B | C | D (*...*)
type mix = Char of letter | Mix of (mix * int) list
我想做一个函数,它计算组合中字母
的出现次数,但很难正确匹配模式
let rec count_char letter mix = match mix with
| Char l -> (*...*)
| Mix (m, i) -> (*...*)
我得到了这个错误
Error: This pattern matches values of type 'a * 'b
but a pattern was expected which matches values of type
(mix * int) list
这并不是说它是一个元组,而是说它是一个元组列表,您试图与单个元组进行匹配Mix((m,i)::)
将起作用,但当然会导致部分匹配,除非您还有一个与空列表匹配的分支。使用Mix((m,i):)
我可以访问第一个元组,但是如何在列表的其余部分递归调用函数count\u char
?用类似rest
的标识符替换\u char
,然后调用count\u char letter rest
u
被称为通配符模式,它将匹配任何内容,但只需忽略它即可。使用标识符也会匹配任何内容,但会将其绑定到标识符名称,在本例中,rest
。rest
不是一个列表吗?此模式需要一个组合
。不确定这是否正确,不能在晚上测试,是的。因此,我想您必须折叠列表,然后在列表中的每个mix
上调用count\u char。