Haskell中的xs Pattern如何工作?

时间:2018-04-27 13:15:12

标签: haskell

此代码如何工作?我没有定义x。

describeList :: [a] -> String
describeList xs = "The list is " ++ case xs of
                                              [ ] -> "empty."
                                              [x] -> "a singleton list."
                                              xs -> "a longer list." 

1 个答案:

答案 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