检查所有参数是否彼此不同

我是 Haskell 的一个完整的初学者,并被困在这个问题上。我想编写一个函数,True如果所有 3 个参数彼此不同,则返回并给出False它们是否相似。

threeArguments :: Int -> Int -> Int -> Bool
threeArguments a b c = if  a /= b && a /= c && b /= c 
    then return true 
    else return False

但我得到错误说

• 无法将预期类型“Bool”与实际类型“m0 a0”匹配

回答

return此处不需要该功能(实际上,您一定不要使用它)。它在 Haskell 中的含义与在大多数其他语言中的含义不同 —— 大概稍后您会看到教程中的那一点。

threeArguments a b c = if a /= b && a /= c && b /= c
    then True
    else False

(我认为你的问题中的true而不是True只是一个转录错误。)

if foo then True else False顺便说一句,这是一个非常常见的初学者反模式。换用就好了foo

threeArguments a b c = a /= b && a /= c && b /= c

而且,只是为了好玩,还有其他实现方式。例如,你可能喜欢

threeArguments a b c = nub [a,b,c] == [a,b,c]

因为它简洁且易于推广到其他参数。

  • @buzzyso Yes, that is suggesting the refactor I did, namely, changing `if foo then True else False` to `foo`. You can't *just* remove the `if` keyword -- you have to remove the `then True else False` part, too.
  • @buzzyso There is no `if`...?

以上是检查所有参数是否彼此不同的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>