尝试使用"stack build"构建:
module Main where
analyzeGold :: Int -> String
analyzeGold standard =
if | standard == 999 -> "Wow! 999 standard!"
| standard == 750 -> "Great! 750 standard."
| standard == 585 -> "Not bad! 585 standard."
| otherwise -> "I don't know such a standard..."
main :: IO ()
main = do
putStrLn (analyzeGold 999)
我得到了:
Multi-way if-expressions need MultiWayIf turned on
|
6 | if | standard == 999 -> "Wow! 999 standard!"
| ^^
如何解决?
堆栈 1.7.1, GHC 8.2.2
在哈斯克尔,只有一个if
-then
-else
子句。如果你想要这些">多假设"语句,你可以使用一个守卫。
使用防护装置
你的语法已经相当接近守卫了,除了它没有if
关键字,并且等号(=
(用于表示在这种情况下的输出是什么。
所以你应该把它重写为:
analyzeGold :: Int -> String
analyzeGold standard
| standard == 999="Wow! 999 standard!"
| standard == 750="Great! 750 standard."
| standard == 585="Not bad! 585 standard."
| otherwise="I don't know such a standard..."
有关守卫的语法和使用的一些信息,请参阅此处 [lyah]。
使用模式s
由于每次检查整数文字的相等性时,我们实际上可以将检查从守卫移动到模式,例如:
analyzeGold :: Int -> String
analyzeGold999= "Wow! 999 standard!"
analyzeGold750= "Great! 750 standard."
analyzeGold585= "Not bad! 585 standard."
analyzeGold_= "I don't know such a standard..."
这里的下划线(_
(充当匹配所有值的通配符(以及所有与前面子句不匹配的模式(。
使用MultiWayIf
扩展
还可以启用 GHCi 扩展以启用此扩展,方法是在文件头中编写杂注,或在调用解释器时使用-XMultiWayIf
。所以:
{-# LANGUAGE MultiWayIf #-}
analyzeGold :: Int -> String
analyzeGold standard =
if | standard == 999 -> "Wow! 999 standard!"
| standard == 750 -> "Great! 750 standard."
| standard == 585 -> "Not bad! 585 standard."
| otherwise -> "I don't know such a standard..."
或:
$ ghci-XMultiWayIf
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Prelude> :{
Prelude| analyzeGold :: Int -> String
Prelude| analyzeGold standard =
Prelude| if | standard == 999 -> "Wow! 999 standard!"
Prelude| | standard == 750 -> "Great! 750 standard."
Prelude| | standard == 585 -> "Not bad! 585 standard."
Prelude| | otherwise -> "I don't know such a standard..."
Prelude| :}