-1

I have a function with signature read_F95_src :: String -> IO [String]. This function is used elsewhere and cannot be changed.

I am reading in source lines and associated with a label as such src_lines = read_F95_src templ_src_name, which compiles and runs fine.

The problem is that I now have a function which takes in [String], and no matter how I try, I can't figure out a way to get the [String] value from src_lines.

Geesh_SO
  • 2,156
  • 5
  • 31
  • 58

3 Answers3

4

You don't "extract" a value from IO. Instead you lift the rest of your computation into IO using fmap. So

read_F95_src :: String -> IO [String]

doSomethingWithStringList :: [String] -> Whatever

fmap doSomethingWithStringList :: IO [String] -> IO Whatever

fmap doSomethingWithStringList . read_F95_src :: String -> IO Whatever

You should get used to this pattern because it's going to happen to you a lot when you use Haskell. For example, if you want to do something with the IO Whatever you'll have to use the same trick again!

Tom Ellis
  • 9,224
  • 1
  • 29
  • 54
1
let src_lines = read_F95_src templ_src_name
(ss::[String]) <- src_lines
{- do whatever with ss -}
Rob Stewart
  • 1,812
  • 1
  • 12
  • 25
1

Extract the [String] like this inside a do block:

some_function :: IO [String]
some_function = do
  dat <- read_F95_src "some data" -- Now the dat will contain the [String]
  -- Now do all your stuffs on dat and return whatever you want to.
  return dat

Once you have extracted the dat inside the function, you can apply other functions on it according to your logic and finally return whatever you need to.

Sibi
  • 47,472
  • 16
  • 95
  • 163
  • Keep in mind that this function will again return an `IO [String]`, so if you want to do something with the list, you need to do it after you read it but before you return it. `dat` is – inside this function – a `[String]` value without the `IO`. – kqr Nov 15 '13 at 14:13
  • But dat is only within the scope of the do is it not? I need to use the `[String]` later in the program. – Geesh_SO Nov 15 '13 at 14:16
  • @Geesh_SO Create functions which operates on `[String]` according to your logic and call it inside this function. This way you will also separate pure and impure code. – Sibi Nov 15 '13 at 14:19