【问题标题】:Invert Return Value of Type IO Bool反转 IO Bool 类型的返回值
【发布时间】:2015-09-26 00:19:55
【问题描述】:

我有一个返回类型IO Bool 的函数。我想将此函数用作filterM 的参数,但我真正想做的是反转它的输出。我已经尝试了(not . f) 的效果,但not 并不符合IO 的氛围。如何反转IO Bool

这是一个最小的工作示例:

#!/usr/bin/env runhaskell
{-# LANGUAGE UnicodeSyntax #-}
module Main where
import Prelude.Unicode

userEnteredStr ∷ String → IO Bool
userEnteredStr str = do
    input ← getLine
    return (input ≡ str)

-- doesn't work. How would I write this function? 
--userDidntEnterStr ∷ String → IO Bool
--userDidntEnterStr str = not . userEnteredStr

main = do result ← userEnteredStr "y"
          print result

对不起,如果这是基本的!我在 Hoogle 上找不到类型为 IO Bool -> IO Bool 的函数,也没有在我的网络搜索中找到任何内容。

【问题讨论】:

  • 尝试使用 (Bool -> Bool) -> (IO Bool -> IO Bool) 代替。它最终得到了正确的答案……我承认,它在列表中很低,但它确实得到了它。 (a -> b) -> (IO a -> IO b) 排在首位。

标签: haskell boolean monads functor


【解决方案1】:

为了记录,“不起作用”不是一个很有帮助的错误描述:) 是语法错误吗?类型错误?它是否编译和类型检查,但返回错误的值?这可能是对您的问题的最模糊的描述......对于任何想要帮助您的人来说,这通常是一个非常非常大的障碍/障碍。

这里的主要问题是您不能将not 应用于IO Bool,因为not 仅适用于Bools。 IO Bool 不是Bool,也不是“包含Bool”,所以它不起作用也就不足为奇了。这就像尝试将(* 2) 应用于您的狗一样。你的狗不是数字!

但您似乎知道如何使用 IO 中的 do 表示法和绑定,所以也许您可以理解为什么会这样?

userDidntEnterStr :: String -> IO Bool
userDidntEnterStr str = do
   didEnter <- userEnteredStr str
   return (not didEnter)

或者,您也可以将任何(a -&gt; b) 应用于IO a结果,以使用fmap 获得新的IO b

userDidntEnterStr :: String -> IO Bool
userDidntEnterStr str = fmap not (userEnteredStr str)

【讨论】:

  • 公平评论,不包括编译器输出是一个菜鸟错误。感谢您的出色回答,我认为 fmap 正是我想要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2021-02-07
相关资源
最近更新 更多