How do I convert a IO [[Int]] to [[Int]] in Haskell? [duplicate] - haskell

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
Convert Haskell IO list to list type
I've tried searching but didn't seem to find a proper answer, is this possible in the first place? Any help in this is appreciated.

This isn't possible. An IO [[Int]] doesn't contain an [[Int]]; it is a description of an imperative program that does IO which, when executed, will produce a result of type [[Int]]. Such a description could never be executed at all, or executed any number of times (to produce an [[Int]] each time, and not necessarily the same one).
Haskell is a pure language, so there is no way to execute an IO description directly; instead, you can compose them into larger descriptions. To cause IO to actually happen, you can define main to be an IO action, which is then executed when the program runs; or you can enter IO actions (like putStrLn "Hello, world!") into GHCi, which will run them.
The simplest way to compose IO actions is with do notation, which you've probably already used. Here's an example:
myAction :: IO [[Int]]
myAction = ...
main :: IO ()
main = do
xs <- myAction
-- now xs is a normal value with type [[Int]]
print xs
See this FAQ and the introduction to IO for more information.

The answer by ehird is correct — a value of type IO [[Int]] is a description of how to get a list of lists of integers. This is also called an action.
To get the [[Int]] you need to perform the action. You can do with the <- operator in do notation. That gives you the result of performing the action and you can then operate on this value as needed. You still need to put the value back into the IO monad sooner or later, though. In concrete code it can look like this:
sumAll :: IO [[Int]] -> IO Int
sumAll io_lists = do
lists <- io_lists
return $ sum $ map sum lists
Here, lists is bound to the result of performing the IO action. You can therefore map sum over it with no problem. The return function from the IO monad puts the valube "back" into the monad so that the return type becomes IO Int. Some monads lets you take values out of the monad, but IO doesn't — it represents side effects and you cannot remove a side effect from your code.

Related

Is print in Haskell a pure function?

Is print in Haskell a pure function; why or why not? I'm thinking it's not, because it does not always return the same value as pure functions should.
A value of type IO Int is not really an Int. It's more like a piece of paper which reads "hey Haskell runtime, please produce an Int value in such and such way". The piece of paper is inert and remains the same, even if the Ints eventually produced by the runtime are different.
You send the piece of paper to the runtime by assigning it to main. If the IO action never comes in the way of main and instead languishes inside some container, it will never get executed.
Functions that return IO actions are pure like the others. They always return the same piece of paper. What the runtime does with those instructions is another matter.
If they weren't pure, we would have to think twice before changing
foo :: (Int -> IO Int) -> IO Int
foo f = liftA2 (+) (f 0) (f 0)
to:
foo :: (Int -> IO Int) -> IO Int
foo f = let x = f 0 in liftA2 (+) x x
Yes, print is a pure function. The value it returns has type IO (), which you can think of as a bunch of code that outputs the string you passed in. For each string you pass in, it always returns the same code.
If you just read the Tag of pure-function (A function that always evaluates to the same result value given the same argument value(s) and that does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.) and then Think in the type of print:
putStrLn :: String -> IO ()
You will find a trick there, it always returns IO (), so... No, it produces effects. So in terms of Referential Transparency is not pure
For example, getLine returns IO String but it is also a pure function. (#interjay contribution), What I'm trying to say, is that the answer depends very close of the question:
On matter of value, IO () will always be the same IO () value for the same input.
And
On matter of execution, it is not pure because the execution of that
IO () could have side effects (put an string in the screen, in this
case looks so innocent, but some IO could lunch nuclear bombs, and
then return the Int 42)
You could understand better with the nice approach of #Ben here:
"There are several ways to explain how you're "purely" manipulating
the real world. One is to say that IO is just like a state monad, only
the state being threaded through is the entire world outside your
program;= (so your Stuff -> IO DBThing function really has an extra
hidden argument that receives the world, and actually returns a
DBThing along with another world; it's always called with different
worlds, and that's why it can return different DBThing values even
when called with the same Stuff). Another explanation is that an IO
DBThing value is itself an imperative program; your Haskell program is
a totally pure function doing no IO, which returns an impure program
that does IO, and the Haskell runtime system (impurely) executes the
program it returns."
And #Erik Allik:
So Haskell functions that return values of type IO a, are actually not
the functions that are being executed at runtime — what gets executed
is the IO a value itself. So these functions actually are pure but
their return values represent non-pure computations.
You can found them here Understanding pure functions in Haskell with IO

How to convert IO Int to String in Haskell?

I'm learning to use input and output in Haskell. I'm trying to generate a random number and output it to another file. The problem is that the random number seems to be returning an IO Int, something that I can't convert to a String using show.
Could someone give me a pointer here?
It's helpful if you show us the code you've written that isn't working.
Anyway, you are in a do block and have written something like this, yes?
main = do
...
writeFile "some-file.txt" (show generateRandomNumberSomehow)
...
You should instead do something like this:
main = do
...
randomNumber <- generateRandomNumberSomehow
writeFile "some-file.txt" (show randomNumber)
...
The <- operator binds the result of the IO Int value on the right to the Int-valued variable on the left. (Yes, you can also use this to bind the result of an IO String value to a String-valued variable, etc.)
This syntax is only valid inside a do block. It's important to note that the do block will itself result in an IO value --- you can't launder away the IO-ness.
dave4420's answer is what you want here. It uses the fact that IO is a Monad; that's why you can use the do notation.
However, I think it's worth mentioning that the concept of "applying a function to a value that's not 'open', but inside some wrapper" is actually more general than IO and more general than monads. It's what we have the Functor class for.
For any functor f (this could, for instance, be Maybe or [] or IO), when you have some value
wrapped :: f t (for instance wrapped :: Maybe Int), you can use fmap to apply a function
t -> t' to it (like show :: Int -> String) and get a
wrappedApplied :: f t' (like wrappedApplied :: Maybe String).
In your example, it would be
genRandomNumAsString :: IO String
genRandomNumAsString = fmap show genRandomNumPlain

Haskell beginner, trying to output a list

I suppose everyone here already has seen one of these (or at least a similar) question, still I need to ask because I couldn't find the answer to this question anywhere (mostly because I don't know what exactly I should be looking for)
I wrote this tiny script, in which printTriangle is supposed to print out the pascal triangle.
fac = product . enumFromTo 2
binomial n k = (product (drop (k-1) [2..n])) `div` (fac (n-k))
pascalTriangle maxRow =
do row<-[0..maxRow-1]
return (binomialRow row)
where
binomialRow row =
do k<-[0..row]
return (binomial row k)
printTriangle :: Int -> IO ()
printTriangle rows = do row<-(triangle)
putStrLn (show row)
where
triangle = pascalTriangle rows
Now for reasons that are probably obvious to the trained eye, but completely shrouded in mystery for me, i get the following error when trying to load this in ghci:
Couldn't match expected type `IO t0' with actual type `[[Int]]'
In a stmt of a 'do' expression: row <- (triangle)
In the expression:
do { row <- (triangle);
putStrLn (show row) }
In
an equation for `printTriangle':
printTriangle rows
= do { row <- (triangle);
putStrLn (show row) }
where
triangle = pascalTriangle rows
what im trying to do is something like I call printTriangle like this:
printTriangle 3
and I get this output:
[1]
[1,1]
[1,2,1]
If anyone could explain to me why what I'm doing here doesn't work (to be honest, I am not TOO sure what exactly I am doing here; I am used to imperative languages and this whole functional programming thingy is still mighty confusing to me), and how I could do it in a less dumb fashion that would be great.
Thanks in advance.
You said in a comment that you thought lists were monads, but now you're not sure -- well, you're right, lists are monads! So then why doesn't your code work?
Well, because IO is also a monad. So when the compiler sees printTriangle :: Int -> IO (), and then do-notation, it says "Aha! I know what to do! He's using the IO monad!" Try to imagine its shock and dispair when it discovers that instead of IO monads, it finds list monads inside!
So that's the problem: to print, and deal with the outside world, you need to use the IO monad; inside the function, you're trying to use lists as the monad.
Let's see how this is a problem. do-notation is Haskell's syntactic sugar to lure us into its cake house and eat us .... I mean it's syntactic sugar for >>= (pronounced bind) to lure us into using monads (and enjoying it). So let's write printTriangle using bind:
printTriangle rows = (pascalTriangle rows) >>= (\row ->
putStrLn $ show row)
Okay, that was straightforward. Now do we see any problems? Well, lets look at the types. What's the type of bind? Hoogle says: (>>=) :: Monad m => m a -> (a -> m b) -> m b. Okay, thanks Hoogle. So basically, bind wants a monad type wrapping a type a personality, a function that turns a type a personality into (the same) monad type wrapping a type-b personality, and ends up with (the same) monad type wrapping a type-b personality.
So in our printTriangle, what do we have?
pascalTriangle rows :: [[Int]] -- so our monad is [], and the personality is [Int]
(\row -> putStrLn $ show row) :: [Int] -> IO () -- here the monad is IO, and the personality is ()
Well, crap. Hoogle was very clear when it told us that we had to match our monad types, and instead, we've given >>= a list monad, and a function that produces an IO monad. This makes Haskell behave like a little kid: it closes its eyes and stomps on the floor screaming "No! No! No!" and won't even look at your program, much less compile it.
So how do we appease Haskell? Well, others have already mentioned mapM_. And adding explicit type signatures to top-level functions is also a good idea -- it can sometimes help you to get compile errors sooner, rather than later (and get them you will; this is Haskell after all :) ), which makes it much much easier to understand the error messages.
I'd suggest writing a function that turns your [[Int]] into a string, and then printing the string out separately. By separating the conversion into a string from the IO-nastiness, this will allow you to get on with learning Haskell and not have to worry about mapM_ & friends until you're good and ready.
showTriangle :: [[Int]] -> String
showTriangle triangle = concatMap (\line -> show line ++ "\n") triangle
or
showTriangle = concatMap (\line -> show line ++ "\n")
Then printTriangle is a lot easier:
printTriangle :: Int -> IO ()
printTriangle rows = putStrLn (showTriangle $ pascalTriangle rows)
or
printTriangle = putStrLn . showTriangle . pascalTriangle
If you want to print elements of a list on new lines you shall see this question.
So
printTriangle rows = mapM_ print $ pascalTriangle rows
And
λ> printTriangle 3
[1]
[1,1]
[1,2,1]
Finally, what you're asking for is seems to be mapM_.
Whenever I'm coding in Haskell I always try declare the types of at least the top-level definitions. Not only does it help by documenting your functions, but also makes it easier to catch type errors. So pascalTriangle has the following type:
pascalTriangle :: Int -> [[Int]]
When the compiler sees the lines:
row<-(triangle)
...
where
triangle = pascalTriangle rows
it will infer that triangle has type:
triangle :: [[Int]]
The <- operator expects it's right-hand argument to be a monad. Because you declared your function to work on IO monad, the compiler expected that triangle had the type:
triangle :: IO something
Which clearly does not match type [[Int]]. And that's kind of what the compiler is trying to tell in it's own twisted way.
As others have stated, that style of coding is not idiomatic Haskell. It looks like the kind of code I would produce in my early Haskell days, when I still had an "imperative-oriented" mind. If you try to put aside imperative style of thinking, and open your mind to the functional style, you will find that you can solve most of your problems in a very elegant and tidy fashion.
try the following from the ghci-prompt:
> let {pascal 1 = [1]; pascal n = zipWith (+) (l++[0]) (0:l) where l = pascal (n-1)}
> putStr $ concatMap ((++"\n") . show . pascal) [1..20]
Your code is very unidiomatic Haskell. In Haskell you use higher order function to build other function. That way you can write very concise code.
Here i combine two list lazily using zipWith to produce the next row of pascals triangle pretty much the way you would compute it by hand. Then concatMap is used to produce a printable string of the triangles which is printed by putStr.

Haskell: I/O and Returning From a Function

Please bear with me as I am very new to functional programming and Haskell. I am attempting to write a function in Haskell that takes a list of Integers, prints the head of said list, and then returns the tail of the list. The function needs to be of type [Integer] -> [Integer]. To give a bit of context, I am writing an interpreter and this function is called when its respective command is looked up in an associative list (key is the command, value is the function).
Here is the code I have written:
dot (x:xs) = do print x
return xs
The compiler gives the following error message:
forth.hs:12:1:
Couldn't match expected type `[a]' against inferred type `IO [a]'
Expected type: ([Char], [a] -> [a])
Inferred type: ([Char], [a] -> IO [a])
In the expression: (".", dot)
I suspect that the call to print in the dot function is what is causing the inferred type to be IO [a]. Is there any way that I can ignore the return type of print, as all I need to return is the tail of the list being passed into dot.
Thanks in advance.
In most functional languages, this would work. However, Haskell is a pure functional language. You are not allowed to do IO in functions, so the function can either be
[Int] -> [Int] without performing any IO or
[Int] -> IO [Int] with IO
The type of dot as inferred by the compiler is dot :: (Show t) => [t] -> IO [t] but you can declare it to be [Int] -> IO [Int]:
dot :: [Int] -> IO [Int]
See IO monad: http://book.realworldhaskell.org/read/io.html
I haven't mentioned System.IO.Unsafe.unsafePerformIO that should be used with great care and with a firm understanding of its consequences.
No, either your function causes side effects (aka IO, in this case printing on the screen), or it doesn't. print does IO and therefore returns something in IO and this can not be undone.
And it would be a bad thing if the compiler could be tricked into forgetting about the IO. For example if your [Integer] -> [Integer] function is called several times in your program with the same parameters (like [] for example), the compiler might perfectly well just execute the function only once and use the result of that in all the places where the function got "called". Your "hidden" print would only be executed once even though you called the function in several places.
But the type system protects you and makes sure that all function that use IO, even if only indirectly, have an IO type to reflect this. If you want a pure function you cannot use print in it.
As you may already know, Haskell is a "pure" functional programming language. For this reason, side-effects (such as printing a value on the screen) are not incidental as they are in more mainstream languages. This fact gives Haskell many nice properties, but you would be forgiven for not caring about this when all you're doing is trying to print a value to the screen.
Because the language has no direct facility for causing side-effects, the strategy is that functions may produce one or more "IO action" values. An IO action encapsulates some side effect (printing to the console, writing to a file, etc.) along with possibly producing a value. Your dot function is producing just such an action. The problem you now have is that you need something that will be able to cause the IO side-effect, as well as unwrapping the value and possibly passing it back into your program.
Without resorting to hacks, this means that you need to get your IO action(s) back up to the main function. Practically speaking, this means that everything between main and dot has to be in the "IO Monad". What happens in the "IO Monad" stays in the "IO Monad" so to speak.
EDIT
Here's about the simplest example I could imagine for using your dot function in a valid Haskell program:
module Main where
main :: IO ()
main =
do
let xs = [2,3,4]
xr <- dot xs
xrr <- dot xr
return ()
dot (x:xs) =
do
print x
return xs

Converting IO Int to Int

I've created a combobox from converting a xmlWidget to a comboBox with the function castTocomboBox and now I want to get the text or the index of the active item. The problem is that if I use the comboBoxGetActive function it returns an IO Int result and I need to know how can I obtain the Int value. I tried to read about monads so I could understand what one could do in a situation like this but I don't seem to understand. I appreciate all the help I can get. I should probably mention that I use Glade and gtk2hs.
As a general rule you write something like this:
do
x <- somethingThatReturnsIO
somethingElseThatReturnsIO $ pureFunction x
There is no way to get the "Int" out of an "IO Int", except to do something else in the IO Monad.
In monad terms, the above code desugars into
somethingThatReturnsIO >>= (\x -> somethingElseThatReturnsIO $ pureFunction x)
The ">>=" operator (pronounced "bind") does the magic of converting the "IO Int" into an "Int", but it refuses to give that Int straight to you. It will only pass that value into another function as an argument, and that function must return another value in "IO". Meditate on the type of bind for the IO monad for a few minutes, and you may be enlightened:
>>= :: IO a -> (a -> IO b) -> IO b
The first argument is your initial "IO Int" value that "comboBoxGetActive" is returning. The second is a function that takes the Int value and turns it into some other IO value. Thus you can process the Int, but the results of doing so never escape from the IO monad.
(Of course there is the infamous "unsafePerformIO", but at your level of knowledge you may be certain that if you use it then you are doing it wrong.)
(Actually the desugaring is rather more complicated to allow for failed pattern matches. But you can pretend what I wrote is true)
Well, there is unsafePerformIO: http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/System-IO-Unsafe.html#v:unsafePerformIO
(If you want to know how to find this method: Go to http://www.haskell.org/hoogle and search for the signature you need, here IO a -> a)
That said, you probably heard of "What happens in IO stays in IO". And there are very good reasons for this (just read the documentation of unsafePerformIO). So you very likely have a design problem, but in order to get help from experienced Haskellers (I'm certainly not), you need to describe your problem more detailed.
To understand what those types are –step by step–, first look up what Maybe and List are:
data Maybe a = Nothing | Just a
data [a] = [] | a : [a]
(Maybe a) is a different type than (a), like (Maybe Int) differs from (Int).
Example values of the type (Maybe Int) are
Just 5 and Nothing.
A List of (a)s can be written as ([ ] a) and as ([a]). Example values of ([Int]) are [1,7,42] and [ ].
Now, an (IO a) is a different thing than (a), too: It is an Input/Output-computation that calculates a value of type (a). In other words: it is a script or program, which has to be executed to generate a value of type (a).
An Example of (IO String) is getLine, which reads a line of text from standard-input.
Now, the type of comboBoxGetActive is:
comboBoxGetActive :: ComboBoxClass self => self -> IO Int
That means, that comboBoxGetActive is a function (->) that maps from any type that has an instance of the type-class ComboBoxClass (primitive type-classes are somehow similar to java-interfaces) to an (IO Int). Each time, this function (->) is evaluated with the same input value of this type (self) (whatever that type is), it results in the same value: It is always the same value of type (IO Int), that means that it is always the same script. But when you execute that same script at different times, it could produce different values of type (Int).
The main function of your program has the type (IO ()), that means that the compiler and the runtime system evaluate the equations that you program in this functional language to the value of main, which will be executed as soon as you start the program.

Resources