gss*_*der 1 haskell functional-programming do-notation
虽然我可以应用一个函数两次并将结果绑定到元组:
let foo :: Num a => a -> a
foo x = x + 1
let (x,y) = (foo 10, foo 20)
Run Code Online (Sandbox Code Playgroud)
这不能在一个do块内完成(至少我不知道如何正确地做到这一点):
let bar :: Num a => a -> IO a
bar x = do
let y = x + 1
return y
let test :: Num a => IO a
test = do
(x,y) <- (bar 10, bar 20)
return y
Run Code Online (Sandbox Code Playgroud)
键入GHCI REPL时出现以下错误:
:29:15:
Couldn't match expected type ‘IO a1’ with actual type ‘(t0, a)’
Relevant bindings include
test :: IO a (bound at :28:5)
In the pattern: (x, y)
In a stmt of a 'do' block: (x, y) <- (bar 10, bar 20)
In the expression:
do { (x, y) <- (bar 10, bar 20);
return y }
:29:24:
Couldn't match type ‘(,) (IO a0)’ with ‘IO’
Expected type: IO (IO a1)
Actual type: (IO a0, IO a1)
In a stmt of a 'do' block: (x, y) <- (bar 10, bar 20)
In the expression:
do { (x, y) <- (bar 10, bar 20);
return y }
In an equation for ‘test’:
test
= do { (x, y) <- (bar 10, bar 20);
return y }
Run Code Online (Sandbox Code Playgroud)
我显然可以用更详细的方法来解决它:
let test' :: Num a => IO a
test' = do
x <- bar 10
y <- bar 20
return y
Run Code Online (Sandbox Code Playgroud)
是否有正确的表达方式test而不是像它一样test'?
import Control.Applicative
test = do (x,y) <- (,) <$> bar 10 <*> bar 20
return y
Run Code Online (Sandbox Code Playgroud)
阿卡(x,y) <- liftA2(,) (bar 10) (bar 20).
当然,对于这个特定的例子(在哪里x被抛弃),它将是相同的,并且更好地写
test = bar 20
Run Code Online (Sandbox Code Playgroud)
我将自由地建议您对代码进行一些更改.这是我的版本:
import Control.Monad
-- no need for the do and let
bar :: Num a => a -> IO a
bar x = return $ x + 1 -- or: bar = return . (1+)
-- liftM2 to make (,) work on IO values
test :: Num a => IO a
test = do (x,y) <- liftM2 (,) (bar 10) (bar 20) -- or: (,) <$> bar 10 <*> bar 20
return y
-- show that this actually works
main :: IO ()
main = test >>= print
Run Code Online (Sandbox Code Playgroud)
您的类型不匹配:您的(bar 10, bar 20)评估类型,Num a => (IO a, IO a)但您将其视为Num a => IO (a, a).通过解除(,)我们使它在IO值上工作并返回一个IO值.
看看这个(GHCi,import Control.Monad得到liftM2):
:t (,)
-- type is :: a -> b -> (a, b)
:t liftM2 (,)
-- type is :: Monad m => m a -> m b -> m (a, b)
Run Code Online (Sandbox Code Playgroud)
在我们的例子中,Monad是IOmonad.因此,最终输出liftM2 (,)将在IOdo-block 内很好地工作,因为它返回一个正确的IO值.
而且,当然你可以用较少的详细解决这个特殊的问题:
test'' = bar 20
Run Code Online (Sandbox Code Playgroud)
PS:请不要IO没有任何理由将东西归还给monad.你完全纯粹的操作看起来不合适,没有合理的方法.