OCaml中未使用的火柴盒 [英] match case unused in OCaml

查看:63
本文介绍了OCaml中未使用的火柴盒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想建立一个类型列表(char,'a list),其中每个char是字母的大写字母.我在get_list上的第二个匹配项中收到警告Warning 11: this match case is unused..我在第一种情况下做了一些打印,发现len到那里的值为0,所以它从不使用第二种情况.发生什么事了?

I want to build a list of type (char, 'a list) list where each char is an upper case letter of the alphabet. I'am getting a warning Warning 11: this match case is unused. for the second match case on get_list. I did some prints on the first case and found out len get's there with value 0, so it never uses the second case. What's happening?

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定义无关.在模式匹配中,您仅定义变量的外观,描述其一般的结构",变量名称用于命名模式匹配的不同部分,并且是新变量.例如,您可以使用列表:

len is a generic pattern, which hasn't anything to do with the len define above. In a pattern matching you define only how the variable should look like, you describe it's general "structure", the variable names are used to name the differents parts of the pattern matching, and are new variables. For example with lists you can do:

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

当您输入"_"时,只能说我不介意它是哪个值,我不需要它".这是元组的另一个示例:

When you put '_' it's only a convention to say "I don't mind which value it is, I don't need it". Here is another example with tuples:

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

解决方案:条件模式匹配

如果要将条件置于模式匹配中,则可以使用when关键字:

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

另一个对元组进行排序"的示例:

Another example that "sort" a tuple:

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

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

Or just use conditions with integers :

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

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

You can also note that you can do pattern matching within functions :

let f (a,b) = a+b

这篇关于OCaml中未使用的火柴盒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆