合并模式匹配案例时出现语法错误
Syntax error when merging pattern matching cases
我编写了以下函数来计算两个列表的笛卡尔积。
let rec descartes a = function
| _ when a = [] -> []
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
但是当我想简化功能时
let rec descartes a = function
| _ when a = [] | [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
我收到语法错误。
根据this,模式匹配的语法是:
pattern-matching ::= [ | ] pattern [when expr] -> expr { | pattern [when
expr] -> expr }
并且你可以找到pattern
here的语法。所以你可以看到 when
不是 pattern
的一部分,这解释了语法错误。
但无论如何,您的代码都是多余的,一旦您拥有 [] -> []
,您就不再需要 _ when a = [] -> []
。所以你可以简单地写:
let rec descartes a = function
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
我编写了以下函数来计算两个列表的笛卡尔积。
let rec descartes a = function
| _ when a = [] -> []
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
但是当我想简化功能时
let rec descartes a = function
| _ when a = [] | [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;
我收到语法错误。
根据this,模式匹配的语法是:
pattern-matching ::= [ | ] pattern [when expr] -> expr { | pattern [when
expr] -> expr }
并且你可以找到pattern
here的语法。所以你可以看到 when
不是 pattern
的一部分,这解释了语法错误。
但无论如何,您的代码都是多余的,一旦您拥有 [] -> []
,您就不再需要 _ when a = [] -> []
。所以你可以简单地写:
let rec descartes a = function
| [] -> []
| t::q -> (List.map (function x -> t, x) a) @ (descartes q a) ;;