此代码如何工作?我没有定义x。
describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of
[ ] -> "empty."
[x] -> "a singleton list."
xs -> "a longer list."
答案 0 :(得分:0)
使用显式括号,您的代码为
describeList :: [a] -> String
describeList xs = "The list is " ++ (case xs of
{ [ ] -> "empty."
; [x] -> "a singleton list."
; xs -> "a longer list." } )
所以你的问题的答案是,这是由case
完成的模式匹配的工作原理:
xs
成功匹配空列表[ ]
时,会使用第一个备选方案。xs
与单个列表[x]
匹配,则执行第二个备选方案,任何模式变量绑定到值<的各个部分< / em>匹配,xs
。