简体   繁体   中英

IO values into haskell function

I currently have a function with definition:

f :: [Int] -> Int -> [[Int]]

And have two variables of type IO [Int] and IO Int. I want to pass these variables to this function f. I am able to do this when it is just one variable being passed to the function, but when it is 2 I can't get it to work.

You can write a do block:

f' ::  [[Int]]
f' = do
    x <- val1
    y <- val2
    return (f x y)

with val1 :: IO [Int] and val2 :: IO Int the values you want to pass as parameters.

or in an applicative style:

f' :: IO [[Int]]
f' = f  val1  val2

or we can make use of liftA2 :: (a -> b -> c) -> fa -> fb -> fc :

f' :: IO [[Int]]
f' =  f val1 val2

You should use <- in do notation and run the function on the unwrapped values.

-- Implementations left out
xsFn :: IO [Int]
xFn :: IO Int

main = do
  xs <- xsFn
  x <- xFn
  -- We've unwrapped the values, so now xs :: [Int] and x :: Int

  let result = f xs x -- result :: [[Int]]
  -- do something with result
  return ()

IO has an Applicative instance, so you can use liftA2 :

> f = undefined :: [Int] -> Int -> [[Int]]
> import Control.Applicative
> :t liftA2 f
liftA2 f :: Applicative f => f [Int] -> f Int -> f [[Int]]

With the TypeApplications extension, you can see it more clearly.

> :set -XTypeApplications
> :t liftA2 @IO f
liftA2 @IO f :: IO [Int] -> IO Int -> IO [[Int]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM