cib*_*en1 19 haskell parentheses
我读到了,你知道你已经知道了
枚举成员是按顺序排序的类型... 此类中的类型:(),Bool,Char ...
它也出现在一些签名中:
putChar :: Char -> IO ()
Run Code Online (Sandbox Code Playgroud)
在Google中很难找到有关它的信息,因为答案是指"常见括号"的问题(用于函数调用,优先级问题等).
因此,表达()意味着什么?这是一种类型吗?什么是类型的变量()?什么用于何时需要?
bhe*_*ilr 25
它既是一种类型,也是一种价值. ()是一个特殊类型"发音" 单位,它有一个值:(),也是发音单位.它与voidJava或C/C++中的类型基本相同.如果您熟悉Python,请将其视为NoneType具有单例的Python None.
当您想要表示不返回任何内容的操作时,它非常有用.它最常用于Monads的上下文中,例如IOmonad.例如,如果您具有以下功能:
getVal :: IO Int
getVal = do
putStrLn "Enter an integer value:"
n <- getLine
return $ read n
Run Code Online (Sandbox Code Playgroud)
由于某种原因,你决定只是想惹恼用户并扔掉他们刚刚传入的号码:
getValAnnoy :: IO ()
getValAnnoy = do
_ <- getVal
return () -- Returns nothing
Run Code Online (Sandbox Code Playgroud)
但是,return它只是一个Monad函数,所以我们可以进一步抽象这个
throwAwayResult :: Monad m => m a -> m ()
throwAwayResult action = do
_ <- action
return ()
Run Code Online (Sandbox Code Playgroud)
然后
getValAnnoy = throwAwayResult getVal
Run Code Online (Sandbox Code Playgroud)
但是,您不必自己编写此函数,它已经存在于更少约束Control.Monad的函数void中并且在Functors上工作:
void :: Functor f => f a -> f ()
void fa = fmap (const ()) fa
Run Code Online (Sandbox Code Playgroud)
为什么它可以Functor代替Monad?好吧,对于每个Monad实例,您可以将Functor实例编写为
instance Monad m => Functor m where
fmap f m = m >>= return . f
Run Code Online (Sandbox Code Playgroud)
但你无法做到Monad每一个Functor.这就像一个正方形是一个矩形,但一个矩形并不总是一个正方形,Monads形成一个Functors的子集.
正如其他人所说,它是具有一个称为单位的值的单位类型.在Haskell语法中,这很容易,如果容易混淆,表示为() :: ().我们也可以很容易地制作自己的.
data Unit = Unit
>>> :t Unit :: Unit
Unit :: Unit
>>> :t () :: ()
() :: ()
Run Code Online (Sandbox Code Playgroud)
这是()因为它的行为非常像"空元组".理论上有理由说明这一点,但老实说它也有很多简单直观的意义.
它经常被用作类型构造函数的参数,如IO或者ST它的有趣值的上下文,而不是值本身.这是直观的,因为如果我告诉你我有类型的价值,()那么你不需要知道更多 - 只有其中一个!
putStrLn :: String -> IO () -- the return type is unimportant,
-- we just want the *effect*
map (const ()) :: [a] -> [()] -- this destroys all information about a list
-- keeping only the *length*
>>> [ (), (), () ] :: [()] -- this might as well just be the number `3`
-- there is nothing else interesting about it
forward :: [()] -> Int -- we have a pair of isomorphisms even
forward = length
backward :: Int -> [()]
backward n = replicate n ()
Run Code Online (Sandbox Code Playgroud)