我需要一个像这样工作的函数:
foo :: Integer -> Integer -> [Integer]
foo a b = do
let result = []
let Coord x y = boo a b
if x > 0
let result = result ++ [3]
if y > 0
let result = result ++ [5]
if x < a
let result = result ++ [7]
if y < b
let result = result ++ [9]
result
我不能使用守卫,因为结果可能有不止一个元素。但正如我所见,我不能在“if”表达式中使用“let”:
all_possible_combinations.hs:41:14: parse error on input `let'
如何检查多个表达式并在列表中添加新元素? 我不仅搜索命令式解决方案,还搜索功能性解决方案。
最佳答案
其他人已经说过为什么您尝试的方法不起作用。这是做你想做的事情的简洁方法:
foo :: Integer -> Integer -> [Integer]
foo a b = map snd (filter fst [(x > 0, 3),
(y > 0, 5),
(x < a, 7),
(y < a, 9)])
where Coord x y = boo a b
那么这是如何工作的呢?
我们从一对列表开始。每对的第二个元素是我们可能希望包含在 foo
的返回值中的值。每对的第一个元素告诉我们是否真的要包含它。
然后我们调用filter fst
,它会丢弃所有条件为假的对。
最后,我们调用 map snd
,它会丢弃条件(所有剩下的都为真),并保留我们感兴趣的值。
关于haskell - 在 'let' 表达式中使用 'if',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3985631/