采用两个看起来相似的函数:
foo :: Eq a => [a] -> Bool
foo [x,y] | x == y = True
foo _ = False
bar :: Eq a => [a] -> Bool
bar _ = False
bar [x,y] | x == y = True
main = do
print $ foo [1,1]
print $ bar [1,1]
用ghc编译的时候,结果是可以预见的:
正确
错误
因为它评估不同模式组的顺序似乎是从上到下的。我的问题是这种行为是在语言本身中定义的还是仅由编译器定义的?例如,如果我使用不同的编译器,我会得到相反的结果吗?我想知道它是否像 C/C++ 中那样可预测或模棱两可
最佳答案
它是在语言本身中定义的。 Subsection 4.4.3.1 of the Haskell Report 2010指定函数定义中的子句等效于 case 表达式。反过来,case 表达式按顺序匹配它们的替代项。引用 section 3.13 of the Report :
A case expression is evaluated by pattern matching the expression e against the individual alternatives. The alternatives are tried sequentially, from top to bottom.
关于haskell - Haskell中模式匹配评估的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52788053/