Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IO values into haskell function

Tags:

io

haskell

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.

like image 628
Jordan Rose Avatar asked Jun 04 '26 13:06

Jordan Rose


2 Answers

You can write a do block:

f' :: IO [[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) -> f a -> f b -> f c:

f' :: IO [[Int]]
f' = liftA2 f val1 val2
like image 88
Willem Van Onsem Avatar answered Jun 07 '26 23:06

Willem Van Onsem


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 ()
like image 40
Steven Fontanella Avatar answered Jun 07 '26 22:06

Steven Fontanella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!