“模式匹配并非详尽无遗”和“此匹配情况未使用”问题

问题描述 投票:0回答:1

我正在编写一个赋值的代码,在我的代码的一部分中,我遇到了有关OCaml中模式匹配的问题,我无法弄明白。

    fun frag -> match make_and_parser t pf frag with
                | (Some children, suffix) -> match make_or_parser (pf h) pf suffix with
                                            | (None, left) -> (Some children, left)
                                            | (Some tree, left) -> (Some (children @ tree), left)
                | (None, suffix) -> match make_or_parser (pf h) pf suffix with
                                    | (None, left) -> (None, left)
                                    | (Some tree, left) -> (Some tree, left))

我得到的错误是这部分

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a case that is not matched:
(None, _)
File "make_parser.ml", line 42, characters 10-24:
Warning 11: this match case is unused.
val make_parser :
'a * ('a -> ('a, 'b) symbol list list) ->
'b list -> (('a, 'b) symbol list, 'b) parse_tree list option = <fun>

我想知道是否有一些我不知道的明显事物

ocaml
1个回答
1
投票

您需要添加括号。使用您的代码,这就是OCaml所看到的:

fun frag ->
    match make_and_parser t pf frag with
    | (Some children, suffix) -> match make_or_parser (pf h) pf suffix with
                                 | (None, left) -> (Some children, left)
                                 | (Some tree, left) -> (Some (children @ tree), left)
                                 | (None, suffix) -> match make_or_parser (pf h) pf suffix with
                                                     | (None, left) -> (None, left)
                                                     | (Some tree, left) -> (Some tree, left))

由此可见,第一种模式匹配是非穷举的。它缺少(None, _)的模式。由此,显而易见的是,在第二模式匹配中存在未使用的匹配情况(即,(None, suffix))。

要解决您的问题:

fun frag ->
    match make_and_parser t pf frag with
    | (Some children, suffix) -> (match make_or_parser (pf h) pf suffix with
                                 | (None, left) -> (Some children, left)
                                 | (Some tree, left) -> (Some (children @ tree), left))
    | (None, suffix) -> (match make_or_parser (pf h) pf suffix with
                        | (None, left) -> (None, left)
                        | (Some tree, left) -> (Some tree, left))

请注意,在模式匹配周围添加了额外的括号。

总之,你被自己的缩进误导了。

© www.soinside.com 2019 - 2024. All rights reserved.