如何在元组构造函数(OCaml)上进行模式匹配

时间:2018-03-20 09:42:09

标签: functional-programming pattern-matching ocaml

我有以下类型:

type letter = A | B | C | D (*...*)
type mix = Char of letter | Mix of (mix * int) list

我想创建一个函数,它会计算lettermix的出现次数,但很难正确地进行模式匹配。

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

1 个答案:

答案 0 :(得分:1)

并不是它是一个元组,它是你正在尝试与单个元组匹配的元组的列表Mix ((m, i) :: _)将起作用,但除非您还有一个与空列表匹配的分支,否则会导致部分匹配。