Lan*_*ton 1 monads haskell boolean functor
我有一个返回类型的函数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
Run Code Online (Sandbox Code Playgroud)
对不起,如果这是基本的!我在Hoogle上找不到类型的功能,但IO Bool -> IO Bool在我的网页搜索中找不到任何内容.
对于记录,"不工作"不是一个非常有用的错误描述:)是语法错误?类型错误?它编译和类型检查,但返回错误的值?这可能是对你的问题最模糊的描述......对于想要帮助你的人来说,这通常是一个非常大的障碍/障碍.
这里的主要问题是,你不能申请not到IO Bool,因为not只适用于Bool秒.一个IO Bool不是Bool,也不是"包含Bool",所以它不起作用就不足为奇了.这就像试图适用(* 2)于你的狗.你的狗不是一个数字!
但似乎你知道如何使用IO的符号和绑定,所以也许你可以理解为什么这会起作用?
userDidntEnterStr :: String -> IO Bool
userDidntEnterStr str = do
didEnter <- userEnteredStr str
return (not didEnter)
Run Code Online (Sandbox Code Playgroud)
另外,您也可以申请任何(a -> b)的结果的IO a一个新获得IO b使用fmap:
userDidntEnterStr :: String -> IO Bool
userDidntEnterStr str = fmap not (userEnteredStr str)
Run Code Online (Sandbox Code Playgroud)