将函数应用程序的结果存储在DO块内的元组中

时间:2015-09-18 08:02:56

标签: haskell functional-programming do-notation

虽然我可以将函数应用两次并将结果绑定到元组中:


  let foo :: Num a => a -> a
      foo x = x + 1

  let (x,y) = (foo 10, foo 20)

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

输入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 }

我显然可以用更详细的方法来解决它:


  let test' :: Num a => IO a
      test' = do
                 x <- bar 10
                 y <- bar 20
                 return y

是否有正确的方法来表达test而不像test'

3 个答案:

答案 0 :(得分:7)

import Control.Applicative

test = do (x,y) <- (,) <$> bar 10 <*> bar 20
          return y

Aka (x,y) <- liftA2(,) (bar 10) (bar 20)

当然,对于这个特定的例子(其中x被丢弃),它就等同而且写得好多了

test = bar 20

答案 1 :(得分:6)

我会自由地建议您对代码进行一些更改。这是我的版本:

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

您的类型不匹配:您的(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)

在我们的例子中,MonadIO monad。因此,liftM2 (,)的最终输出将在IO do-block中很好地工作,因为它返回正确的IO值。

当然,你可以用较少的详细解决这个特殊问题:

test'' = bar 20

PS:请不要在没有任何理由的情况下将内容返回IO monad。你制作完全纯粹的操作看起来不合适,而且没有合理的方法。

答案 2 :(得分:1)

你需要一个辅助函数来从元组内部提升IO 为了简洁起见,我将使用Int代替Num a => a

(bar 1, bar 2) :: (IO Int, IO Int)

因此你需要带签名的东西

liftTuple :: (IO x, IO y) -> IO (x, y)
liftTuple (mx, my) = ...

然后你可以做(x,y) <- liftTuple (bar 1, bar 2)