【发布时间】:2013-11-30 14:09:18
【问题描述】:
这里有两个非常简单的函数f 和g。
{-# LANGUAGE ScopedTypeVariables #-}
module Test where
import Control.Applicative
f :: IO ()
f = do
y <- (<*>) (pure (show . (*10))) (read <$> readFile "data")
writeFile "out" y
g :: IO ()
g = do
y <- (readFile "data" >>= return . show . (*10) . read)
writeFile "out" y
f中读取的文件和*10以pure和(<*>)的应用样式写入。 g 中读取的文件和*10 以单子样式编写,带有>>=。 (我故意避免在g 中使用liftM 来强调下面的问题)。
f 和 g 之间的语义区别是什么?或者在这种情况下,它只是一种风格选择吗?
【问题讨论】:
-
一元风格至少在我看来更具可读性:)
-
你可以把
(<*>) (pure (show . (*10))) (read <$> readFile "data")写成show . (*10) . read <$> readFile "data" -
<-和g中的return基本上相互抵消,do { y <- readFile "data"; writeFile "out" (show . (*10) . read $ y) }会更短(并且可以说不那么做作)。
标签: haskell monads applicative