ocaml - OCaml 中未使用大小写匹配

标签 ocaml

我想构建一个 (char, 'a list) 类型的列表,其中每个字符都是字母表中的大写字母。我收到警告 Warning 11: this match case is unused.对于 get_list 上的第二个匹配情况。我对第一个案例做了一些打印,发现len get 的值为 0,因此它从不使用第二种情况。发生什么事了?

let rec get_list abc i len = 
  match i with 
  | len -> []
  | _ -> ((String.get abc i), [])::get_list abc (i + 1) len

in

let rec print_list l = 
  match l with
  | [] -> ()
  | h::t -> print_char(fst h);print_list t
in

let abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" in
let abc_l = get_list abc 0 (String.length abc) in
print_list abc_l;;

最佳答案

它不起作用的原因

当你写的时候

match i with 
  | len -> []
  | _ -> ["..."]

len 是一个通用模式,与上面的 len 定义没有任何关系。在模式匹配中,您仅定义变量的外观,描述它的一般“结构”,变量名称用于命名模式匹配的不同部分,并且是新变量。例如,对于列表,您可以执行以下操作:

match my_list with 
  | [x,y,z] -> x+y+z
  | x :: r  -> x + (List.length r)
  | anything_else -> List.length anything_else

当你输入“_”时,这只是一种约定,即“我不介意它是什么值,我不需要它”。这是元组的另一个示例:

match my_tuple with 
  | (a,b) -> a+b

解决方案:条件模式匹配

如果您想在模式匹配中添加条件,您可以使用 when 关键字:

match i with 
  | n when n = len -> []
  | _ -> ["..."]

“排序”元组的另一个示例:

match my_tuple with 
  | (a,b) when a>b -> (a,b)
  | (a,b)          -> (b,a)

或者只使用带有整数的条件:

if i = len then []
else ["..."]

您还可以注意到,您可以在函数内进行模式匹配:

let f (a,b) = a+b

关于ocaml - OCaml 中未使用大小写匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967427/

相关文章:

ocaml:什么是括号中有关键字 val 的表达式?

f# - 将 OCaml 转换为 F# : OCaml equivalent of F# spec, 专门初始化

module - 跨模块的类型定义

ocaml - 在 OCaml 中使用 GADT 的简单 lambda 演算 DSL

list - 如何在 ocaml 中一次遍历两个列表?

emacs - OCaml Emacs Tuareg : Evaluate phrase keyboard shortcut, 以及如何显示实际的希腊符号?

regex - OCaml:如何从字符串中删除所有非字母字符?

functional-programming - 关于 OCaml 模式匹配语法

multicore - 如何在 Ocaml 中使用多核进行蒙特卡罗模拟?

c# - 是否有一种语言同时允许静态和动态类型?