Haskell: I/O and Returning From a Function - haskell

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

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

Solving linear equations - Math.LinearEquationSolver returns IO(Maybe[Rational])

I am writing a program to solve certain mathematical problems, and Haskell is the language I've written it in so far (for various reasons). At one point, I need to solve a system of linear equations, and then use the result for something else. I can give more details if needed, but didn't want to go crazy at first.
The easiest way I could find of solving linear equations was to use the Math.LinearEquationSolver module from the linearEqSolver package on hackage. Everything works fine, except that all of the methods (e.g. solveRationalLinearEqs) have a return type of IO (Maybe [Rational]). I want to be able to feed the solution into a method which accepts [Rational].
I know that the whole point of IO is that you can't just take stuff out of it and put it back in, but I haven't written Haskell in enough years now that I've forgotten all of what I used to know about IO.
Is there an easy explanation/example of what I should do? Is the simplest solution to use some other module/find some other way of solving the system of equations?
Edit: I have tried using the HMatrix method linearSolveLS but this returns a list of type [Double] (and is also nowhere near accurate enough for what I need, even if I did settle for a non-fractional type), whereas I would really prefer the return to be of type [Rational] (as in LinearEquationSolver).
The most idiomatic way to do this is to use >>= to combine the IO action that produces your result with the rest of your program.
(>>=) :: Monad m => m a -> (a -> m b) -> m b
(>>=) :: IO (Maybe [Rational]) -> ((Maybe [Rational]) -> IO a) -> IO a
You would use it like this:
(linearEqSolver arg1 arg2 arg3 ... argn) >>= \maybeResult -> case maybeResult of
Just resultList -> (... :: IO a)
Nothing -> (... :: IO a)
Alternatively, if the rest of your code doesn't need IO, you can use fmap, or its infix synonym <$> to map a pure function over the result of linearEqSolver.
theRestOfYourCode :: Maybe [Rational] -> a
(theRestOfYourCode <$> (linearEqSolver arg1 arg2 ... argn)) :: IO a
Note: Most of these type signatures are just for clarity, and can be inferred.
You could also use the Monad instance for Maybe in the same way, but pattern matching is clearer in this case, since it is hard to mentally parse expressions that use multiple Monad instances in general.

Expected Type and Main

Total Haskell noob here. I have a simple function, and a main. I don't have any idea what this error means:
Couldn't match expected type `IO t0' with actual type `Bool'
In the expression: main
When checking the type of the function `main'
when compiling the code:
is_instructor :: String -> Bool
is_instructor "Jeremy Erickson" = True
is_instructor x = False
main :: Bool
main = is_instructor "foo"
main is the thing that gets called when you run your programme. It is expected that a programme does in some way interact with the outside world (read input, print output, such things), therefore it's reasonable that a main should have the type IO something. For reasons of type safety and simplicity, that is a requirement in Haskell, like main in Java must have type public static void main(String[] arrgh).
You probably wanted you value to be printed, so
main :: IO ()
main = print $ is_instructor "foo"
would be what you want.
You can't have a main function with type Bool, it always needs to be in the IO monad. What you probably want is something like printing out this boolean value. Then just do that!
main :: IO()
main = print $ is_instructor "foo"
You've certainly heard that Haskell is a purely functional language. This means (among other things) that the only thing that a function can do in Haskell is compute a result that depends on the arguments; a function can't do I/O, or have a result that depends on something other than the arguments' values.
But Haskell allows you to write programs that do I/O and other effectful things. How is this possible? Well, what it means is that in Haskell, things that perform I/O or side effects are not functions; they are something else. People often refer to them as actions. I/O actions in Haskell have types of the form IO a.
The error you're getting here is that main, the entry point to a Haskell program, is required to be an action of type IO (). But is_instructor is a function of type String -> Bool, and is_instructor "foo" is a Bool.
Haskell doesn't allow you mix and match pure functions and actions haphazardly like that. Applying a function and executing an action are two different things, and will require different code.

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

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.

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