I have a homework to sort a numbers that are to extract from a file.
Simple File Format:
45673
57879
28392
54950
23280
...
So I want to extract [Int] and than to apply my sort-function radix to it.
I write in my file
readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
makeInteger :: [String] -> [Int]
makeInteger = map read
and then I write in the command line
radix (makeInteger (readlines("111.txt")))
and then I have, off course, problems with type conversion from IO String to String. I tried to write
makeInteger :: IO [String] -> [Int]
makeInteger = map read
but it also doesn't work.
How do I work with pure data outside the IO monad?
According to this, "the inability to "escape" from the monad is essential for monads like IO".
So you need to do something like:
readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
makeInteger :: [String] -> [Int]
makeInteger = map read
main = do
content <- readLines "111.txt"
return (radix $ makeInteger content)
This "takes the content out" of the IO monad, applies the function you want on it, then puts it back into the IO monad again.
Related
Okay, I'm new to the Haskell community having come from Python and this is driving me crazy.
I have a text file looking something like:
"1.2
1.423
2.43".
I want to read this text file and store it as a list of doubles in list_var. So list_var = [1.2,1.423,2.43]. This list_var will be used further in the program.
I just don't seem to find an answer on how to do this, most answers can print out list_var, e.g. Haskell - Read a file containing numbers into a list but I need list_var further down the line!
I have tried:
get_coefficients :: String -> [Double]
get_coefficients file_1 = do
coefficients_fromfile <- readLines "test2.txt"
let coefficients = map readDouble coefficients_fromfile
return coefficients
which doesn't work, readLines is
readLines :: FilePath -> IO [String]
readLines = fmap lines . readFile
and readDouble is
readDouble :: String -> Double
readDouble = read
Thanks in advance!
Since you use return, your output is in a monad, in this case the IO monad. As the error message tells you, you should change this line:
get_coefficients :: String -> [Double]
To this:
get_coefficients :: String -> IO [Double]
This is because of a core principle of Haskell: referential transparency.
If you want to use the [Double] produced, you still have to keep it in an IO monad, like so:
main :: IO ()
main = do
-- This can be thought of as taking out values from the monad,
-- but requires the promise that it'll be put back into a monad later.
doubles <- get_coefficients "This argument does nothing, why?"
-- This prints the list of doubles. Note: it returns an IO (),
-- thus fufills the promise!
-- print :: Show a => a -> IO ()
print doubles
I am having trouble reading in a level file in Haskell. The goal is to read in a simple txt file with two numbers seperated by a space and then commas. The problem I keep getting is this: Couldn't match type `IO' with `[]'
If I understand correctly the do statement is supposed to pull the String out of the Monad.
readLevelFile :: FilePath -> [FallingRegion]
readLevelFile f = do
fileContent <- readFile f
(map lineToFallingRegion (lines fileContent))
lineToFallingRegion :: String -> FallingRegion
lineToFallingRegion s = map textShapeToFallingShape (splitOn' (==',') s)
textShapeToFallingShape :: String -> FallingShape
textShapeToFallingShape s = FallingShape (read $ head numbers) (read $ head
$ tail numbers)
where numbers = splitOn' (==' ') s
You can't pull things out of IO. You can think of IO as a container (in fact, some interpretations of IO liken it to the box containing Schrödinger's cat). You can't see what's in the container, but if you step into the container, values become visible.
So this should work:
readLevelFile f = do
fileContent <- readFile f
return (map lineToFallingRegion (lines fileContent))
It does not, however, have the type given in the OP. Inside the do block, fileContent is a String value, but the entire block is still inside the IO container.
This means that the return type of the function isn't [FallingRegion], but IO [FallingRegion]. So if you change the type annotation for readLevelFile to
readLevelFile :: FilePath -> IO [FallingRegion]
you should be able to get past the first hurdle.
Let's look at your first function with explicit types:
readLevelFile f = do
(fileContent :: String) <-
(readFile :: String -> IO String) (f :: String) :: IO String
fileContent is indeed of type String but is only available within the execution of the IO Monad under which we are evaluating. Now what?
(map lineToFallingRegion (lines fileContent)) :: [String]
Now you are suddenly using an expression that is not an IO monad but instead is a list value - since lists are also a type of monad the type check tries to unify IO with []. What you actually wanted is to return this value:
return (map lineToFallingRegion (lines fileContent)) :: IO [String]
Now recalling that we can't ever "exit" the IO monad your readLevelFile type must be IO - an honest admission that it interacts with the outside world:
readLevelFile :: FilePath -> IO [FallingRegion]
This question already has answers here:
How to flatten IO [[String]]?
(2 answers)
Closed 7 years ago.
I would like to look in my current directory and only print .zip files.
My strategy (shown below) is to get the FilePaths as an IO [FilePath]. I thought I could lift the IO so that it would be possible to filter on string elements.
What is wrong in my thinking? I wonder if it is a problem that I use liftIO on an IO [FilePath] instead of IO FilePath.
import System.Directory
import System.FilePath.Glob
import Control.Monad.IO.Class
main :: IO()
listCompressedImages folder =
filter (match (compile ".zip")) (liftIO (getDirectoryContents folder))
main = listCompressedImages "." >>= print
You don't want to use liftIO here, that's for lifting an IO action to a more complex monad, not for extracting a value from an IO action. In short, you can't turn IO a into a. The whole point of IO is to prevent you from doing this. You can work with the a value directly using do notation, though:
listCompressedImages :: FilePath -> IO [FilePath]
listCompressedImages folder = do
-- getDirectoryContents :: FilePath -> IO [FilePath]
-- contents :: [FilePath]
contents <- getDirectoryContents folder
-- filter (match (compile ".zip")) :: [FilePath] -> [FilePath]
return $ filter (match (compile ".zip")) contents
main :: IO ()
main = do
-- compressedImages :: [FilePath]
compresssedImages <- listCompressedImages "."
print compressedImages
Whenever you have something with the type IO a and you want to get the value of type a from it, use do notation and extract it using <-. For a more in-depth explanation I'll defer to Learn You a Haskell.
You can not extract anything from IO, but you can adapt the other functions to work on IO values
listCompressedImages folder =
filter (match (compile ".zip")) `fmap` getDirectoryContents folder
The above fmap applies a pure function (as filter ...) to some IO value. Note that the resulting type will still be IO -- again, you can never escape the IO monad.
I have a file number.txt which contains a large number and I read it into an IO String like this:
readNumber = readFile "number.txt" >>= return
In another function I want to create a list of Ints, one Int for each digit…
Lets assume the content of number.txt is:
1234567890
Then I want my function to return [1,2,3,4,5,6,7,8,9,0].
I tried severall versions with map, mapM(_), liftM, and, and, and, but I got several error messages everytime, which I was able to reduce to
Couldn't match expected type `[m0 Char]'
with actual type `IO String'
The last version I have on disk is the following:
module Main where
import Control.Monad
import Data.Char (digitToInt)
main = intify >>= putStrLn . show
readNumber = readFile "number.txt" >>= return
intify = mapM (liftM digitToInt) readNumber
So, as far as I understand the error, I need some function that takes IO [a] and returns [IO a], but I was not able to find such thing with hoogle… Only the other way round seemes to exist
In addition to the other great answers here, it's nice to talk about how to read [IO Char] versus IO [Char]. In particular, you'd call [IO Char] "an (immediate) list of (deferred) IO actions which produce Chars" and IO [Char] "a (deferred) IO action producing a list of Chars".
The important part is the location of "deferred" above---the major difference between a type IO a and a type a is that the former is best thought of as a set of instructions to be executed at runtime which eventually produce an a... while the latter is just that very a.
This phase distinction is key to understanding how IO values work. It's also worth noting that it can be very fluid within a program---functions like fmap or (>>=) allow us to peek behind the phase distinction. As an example, consider the following function
foo :: IO Int -- <-- our final result is an `IO` action
foo = fmap f getChar where -- <-- up here getChar is an `IO Char`, not a real one
f :: Char -> Int
f = Data.Char.ord -- <-- inside here we have a "real" `Char`
Here we build a deferred action (foo) by modifying a deferred action (getChar) by using a function which views a world that only comes into existence after our deferred IO action has run.
So let's tie this knot and get back to the question at hand. Why can't you turn an IO [Char] into an [IO Char] (in any meaningful way)? Well, if you're looking at a piece of code which has access to IO [Char] then the first thing you're going to want to do is sneak inside of that IO action
floob = do chars <- (getChars :: IO [Char])
...
where in the part left as ... we have access to chars :: [Char] because we've "stepped into" the IO action getChars. This means that by this point we've must have already run whatever runtime actions are required to generate that list of characters. We've let the cat out of the monad and we can't get it back in (in any meaningful way) since we can't go back and "unread" each individual character.
(Note: I keep saying "in any meaningful way" because we absolutely can put cats back into monads using return, but this won't let us go back in time and have never let them out in the first place. That ship has sailed.)
So how do we get a type [IO Char]? Well, we have to know (without running any IO) what kind of IO operations we'd like to do. For instance, we could write the following
replicate 10 getChar :: [IO Char]
and immediately do something like
take 5 (replicate 10 getChar)
without ever running an IO action---our list structure is immediately available and not deferred until the runtime has a chance to get to it. But note that we must know exactly the structure of the IO actions we'd like to perform in order to create a type [IO Char]. That said, we could use yet another level of IO to peek at the real world in order to determine the parameters of our action
do len <- (figureOutLengthOfReadWithoutActuallyReading :: IO Int)
return $ replicate len getChar
and this fragment has type IO [IO Char]. To run it we have to step through IO twice, we have to let the runtime perform two IO actions, first to determine the length and then second to actually act on our list of IO Char actions.
sequence :: [IO a] -> IO [a]
The above function, sequence, is a common way to execute some structure containing a, well, sequence of IO actions. We can use that to do our two-phase read
twoPhase :: IO [Char]
twoPhase = do len <- (figureOutLengthOfReadWithoutActuallyReading :: IO Int)
putStrLn ("About to read " ++ show len ++ " characters")
sequence (replicate len getChar)
>>> twoPhase
Determining length of read
About to read 22 characters
let me write 22 charac"let me write 22 charac"
You got some things mixed up:
readNumber = readFile "number.txt" >>= return
the return is unecessary, just leave it out.
Here is a working version:
module Main where
import Data.Char (digitToInt)
main :: IO ()
main = intify >>= print
readNumber :: IO String
readNumber = readFile "number.txt"
intify :: IO [Int]
intify = fmap (map digitToInt) readNumber
Such a function can't exists, because you would be able to evaluate the length of the list without ever invoking any IO.
What is possible is this:
imbue' :: IO [a] -> IO [IO a]
imbue' = fmap $ map return
Which of course generalises to
imbue :: (Functor f, Monad m) => m (f a) -> m (f (m a))
imbue = liftM $ fmap return
You can then do, say,
quun :: IO [Char]
bar :: [IO Char] -> IO Y
main = do
actsList <- imbue quun
y <- bar actsLists
...
Only, the whole thing about using [IO Char] is pointless: it's completely equivalent to the much more straightforward way of working only with lists of "pure values", only using the IO monad "outside"; how to do that is shown in Markus's answer.
Do you really need many different helper functions? Because you may write just
main = do
file <- readFile "number.txt"
let digits = map digitToInt file
print digits
or, if you really need to separate them, try to minimize the amount of IO signatures:
readNumber = readFile "number.txt" --Will be IO String
intify = map digitToInt --Will be String -> [Int], not IO
main = readNumber >>= print . intify
This question already has answers here:
A Haskell function of type: IO String-> String
(4 answers)
Closed 9 years ago.
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.
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!
let src_lines = read_F95_src templ_src_name
(ss::[String]) <- src_lines
{- do whatever with ss -}
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.