gpt4 book ai didi

haskell - 如何在 Haskell 中使用没有 else 条件的 if-then-else 语句?

转载 作者:行者123 更新时间:2023-12-02 02:16:56 25 4
gpt4 key购买 nike

我有一份关系 list ,我想打印所有父亲的名字。由于没有else条件下,以下代码不起作用:

relations = [("father", "arushi", "anandan"), ("mother", "arushi", "abigale"), ("father", "anandan", "ayuta"), ("mother", "anandan", "akanksha")]

father ((r, c, f):xs) = if r == "father" then print(f)

main = do
father (relations)

我不想在 else 之后发表任何声明.

最佳答案

太糟糕了,全部if s 附带 else s。不过没关系,有尊贵的无为IO行动。

father ((r, c, f):xs) = if r == "father" then print f else return ()

还有很多其他方法可以剥这只猫的皮。一是模式匹配。
father (("father", c, f):xs) = print f
father ((r, c, f):xs) = return ()

另一个特定于一元 Action 的方法是使用 when .
father ((r, c, f):xs) = when (r == "father") (print f)

当然,这只是隐藏 else ,这又是 return () :
when p act = if p then act else pure () -- okay, it's actually pure, not return

关于haskell - 如何在 Haskell 中使用没有 else 条件的 if-then-else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com