Pau*_*-AG 9 haskell pattern-matching
为什么此功能总是成功?它始终True以任何值和任何类型返回。这是正确的行为吗?
f a b = case a of b -> True; _ -> False
Run Code Online (Sandbox Code Playgroud)
Wil*_*sem 24
在b的情况下的定义是不是该b在的头部f定义。您创建了一个新的本地范围的变量。因此,您的代码等效于:
f a b = case a of
c -> True
_ -> FalseRun Code Online (Sandbox Code Playgroud)
实际上,使用变量进行模式匹配总是可以成功。
如果要检查两个值是否相同,则需要定义一些函数(Eq例如让Haskell自动派生)。
注意:您可以打开
-Wname-shadowing警告,以使编译器警告您创建会遮盖现有标识符的标识符。例如,您的代码将产生:Run Code Online (Sandbox Code Playgroud)Prelude> f a b = case a of b -> True; _ -> False <interactive>:1:19: warning: [-Wname-shadowing] This binding for ‘b’ shadows the existing binding bound at <interactive>:1:5
除了接受完美的答案外,我还有两分钱:
这个:
f a b = case a of b -> True; _ -> False -- (A)
Run Code Online (Sandbox Code Playgroud)
和这个:
f a b = case a of
c -> True
_ -> False --(B)
Run Code Online (Sandbox Code Playgroud)
等效于:
f a b = case a of
_ -> True
Run Code Online (Sandbox Code Playgroud)
要么
f a b = True
Run Code Online (Sandbox Code Playgroud)
要么
f _ b = True
Run Code Online (Sandbox Code Playgroud)
因此,请小心,因为这是您创建的真实行为,该函数需要两个参数并始终返回True。
也:
如果使用(A)和(B)将显示此警告-Woverlapping-patterns:
warning: [-Woverlapping-patterns]
Pattern match is redundant
In a case alternative: _ -> ...
|
3 | _ -> False
| ^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
791 次 |
| 最近记录: |