Haskell“什么都不做"IO,或者如果没有其他 [英] Haskell "do nothing" IO, or if without else

查看:20
本文介绍了Haskell“什么都不做"IO,或者如果没有其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Haskell 中做一些看起来像这样的事情:

I want to do something in Haskell that looks like this:

main1 = do s <- getLine
           if s == "foo" then putStr "You entered foo"

显然这是不合法的,因为没有 else.我想到的一种选择:

Obviously this isn't legal since there's no else. One alternative I've thought of:

nop :: IO ()
nop = sequence_ []

main2 = do s <- getLine
           if s == "foo" then putStr "You entered foo" else nop

这有点冗长,但如果有必要,我会接受.不过,如果没有 nop 的内置版本,我会感到惊讶.

This is a little verbose, but I would settle for it if necessary. I would be surprised if there weren't a built-in version of nop, though.

或者:

doIf :: Bool -> IO () -> IO ()
doIf b m = if b then m else nop

main3 = do s <- getLine
           doIf (s == "foo") (putStr "You entered foo")

这样比较简洁,但是语法不是特别好.同样,我不会惊讶地发现已经存在的内置内容.

This is more concise, but the syntax is not particularly nice. Again, I wouldn't be surprised to find something built-in that already exists.

执行此操作的首选方法是什么?

What's the preferred way to do this?

推荐答案

在 monad 中执行 no-op 的最简单方法是:

The easiest way to do a no-op in a monad is:

return ()

相当于:

pure ()

但是,对于您正在使用的特定习语,已经为您制作了一个组合器:

However, for the particular idiom you're doing, there's a combinator already made for you:

import Control.Monad
main = do s <- getLine
          when (s == "foo") $ putStr "You entered foo"

这个when 组合器的行为与您的 doIf 组合器完全一样:)

This when combinator behaves exactly like your doIf combinator :)

这篇关于Haskell“什么都不做"IO,或者如果没有其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆