【发布时间】:2020-03-26 01:16:09
【问题描述】:
您好,我是 Haskell 的新手,我认为我的问题很简单,但对我来说很重要。
这行得通:
module Main where
main :: IO ()
main = do
inp <- getLine
let output i | odd i = "Alice" | even i = "Bob" | otherwise = "Weird"
putStrLn (output (read inp))
这不起作用
module Main where
main :: IO ()
main = do
inp <- getLine
let output i
| odd i = "Alice"
| even i = "Bob"
| otherwise = "Weird"
putStrLn (output (read inp))
我知道的: 在你声明的每个函数之前,你会在里面写“let”还是“let”,而不是写“in”。此外,当我将输出编写为非本地函数时,它也起作用了。
我错过了什么?
编辑: 你会推荐这样写吗?
module Main where
main :: IO ()
main = do
inp <- getLine
let
output i
| odd i = "Alice"
| even i = "Bob"
putStrLn (output (read inp))
【问题讨论】:
-
你应该缩进守卫,所以至少比
output多一个空格。 -
他们不是已经缩进了吗?它们比输出多 4 个空格
-
不,现在它们处于
let级别,因此它们具有与output相同的缩进。由于守卫“属于”output函数,因此您需要比output缩进更多。 -
您上次的编辑没问题。如果您愿意,可以将
let output i放在第一行。如果你只在inp上使用output函数,你可以去掉i参数,直接使用inp。我强烈建议以otherwise而不是even i结尾。此外,在编译期间使用-Wall打开警告。
标签: haskell io functional-programming guard