Haskell Return Doesn't Match Expected - haskell

Could someone tell me why the following code doesn't work?
test :: String
test =
do
return ("Hi")
I've been struggling to make the do statement work for a while now, and I've chased it down to this problem. I know this isn't how you ought to make a constant, but this neatly sums up the problem I've been getting.
I get the following error:
Test.hs:5:21:
Couldn't match expected type `Char' with actual type `[Char]'
In the first argument of `return', namely `("Hi")'
In a stmt of a 'do' block: return ("Hi")
In the expression: do { return ("2") }
Update: Ah I see. In my effort to abstract down to the part that was causing me the problem I just created another one. Despite that, this did inadvertently cause me to solve the problem anyway.

GHCi gives the following:
:t do {return ("Hi")}
do {return ("Hi")} :: Monad m => m [Char]
Which means do {return ("Hi")} is not of type String a.k.a. [Char], but of Monad m => m [Char].
A list is a monad, so it takes care of the Monad m in the type but leaves [Char]; but after the list is taken away from the String, what's left is just Char, which cannot match the [Char], so the error results.

return in Haskell is not a keyword--it's just a normal function which happens to have that name. In functions, the expression is returned automatically:
test :: String
test = "Hi"
This is true even if your function take an argument:
double x = 2 * x
It seems you're really new to Haskell. You should read a nice book like "Learn You a Haskell" to get acquainted with it because it is literally nothing like any other language you've ever used, so your existing experience won't be very helpful.

To define a constant value (within a module) you just need
test :: String
test = "Hi"
But I guess that you are trying to do IO.
Please, Learn you a Haskell for the Great Good!

Related

Converting String to Tuple Haskell

I'm trying to create a function for a board game that will read a position on the board as a string and convert to a coordinate that can be used in the program e.g. "D4 => (3,3), "F2" => (5,1)".
So far I have this:
getCoord :: String -> Maybe(Int, Int)
getCoord s =
let alphas = "ABCDEFGH"
coord1 = head(s)
coord2 = tail(s)
in ((elemIndex coord1 alphas)-1, read(head coord2)-1)
I'm still learning about the use of Maybe in Haskell and am encountering the error:
• Couldn't match expected type ‘Maybe (Int, Int)’
with actual type ‘(Maybe Int, Integer)’
• In the expression:
((elemIndex coord1 alphas) - 1, read (head coord2) - 1)
Would appreciate your help on where I might be going wrong.
Thanks!
The problem you're facing is that elemIndex returns a Maybe Int. Since you're also trying to return a Maybe type, the best way to work with this is using a do block to perform operations inside the Maybe monad. This lets you use Maybe values as if they were normal values as long as your output will get wrapped back up in a Maybe. (If you need more information about how monads work, there are plenty of good answers here explaining it, and lots of other great posts across the internet.)
import Text.Read (readMaybe)
import Data.List (elemIndex)
getCoords :: String -> Maybe(Int, Int)
getCoords (coord1:coord2) = do
let alphas = "ABCDEFGH"
row <- elemIndex coord1 alphas
col <- readMaybe coord2
return (row, col - 1)
getCoords _ = Nothing
Note a couple other differences from your original.
The use of readMaybe instead of read. readMaybe is a special version of read that returns a value of type Maybe a. Since we're already working in a Maybe context, it's better to have a no-parse return Nothing than throw an error.
No - 1 on the row. elemIndex already has the behavior you want, i.e. A will return 0, etc.
Pattern match instead of head and tail. This lets you account for the case where the string is empty.
Extra definition to match empty list and return Nothing. The advantage of using a Maybe type is that you can return a value for errors instead of getting a Runtime error. In order to make use of that, we have to make sure we handle all of the cases.

How does return statement work in Haskell? [duplicate]

This question already has answers here:
What's so special about 'return' keyword
(3 answers)
Closed 5 years ago.
Consider these functions
f1 :: Maybe Int
f1 = return 1
f2 :: [Int]
f2 = return 1
Both have the same statement return 1. But the results are different. f1 gives value Just 1 and f2 gives value [1]
Looks like Haskell invokes two different versions of return based on return type. I like to know more about this kind of function invocation. Is there a name for this feature in programming languages?
This is a long meandering answer!
As you've probably seen from the comments and Thomas's excellent (but very technical) answer You've asked a very hard question. Well done!
Rather than try to explain the technical answer I've tried to give you a broad overview of what Haskell does behind the scenes without diving into technical detail. Hopefully it will help you to get a big picture view of what's going on.
return is an example of type inference.
Most modern languages have some notion of polymorphism. For example var x = 1 + 1 will set x equal to 2. In a statically typed language 2 will usually be an int. If you say var y = 1.0 + 1.0 then y will be a float. The operator + (which is just a function with a special syntax)
Most imperative languages, especially object oriented languages, can only do type inference one way. Every variable has a fixed type. When you call a function it looks at the types of the argument and chooses a version of that function that fits the types (or complains if it can't find one).
When you assign the result of a function to a variable the variable already has a type and if it doesn't agree with the type of the return value you get an error.
So in an imperative language the "flow" of type deduction follows time in your program Deduce the type of a variable, do something with it and deduce the type of the result. In a dynamically typed language (such as Python or javascript) the type of a variable is not assigned until the value of the variable is computed (which is why there don't seem to be types). In a statically typed language the types are worked out ahead of time (by the compiler) but the logic is the same. The compiler works out what the types of variables are going to be, but it does so by following the logic of the program in the same way as the program runs.
In Haskell the type inference also follows the logic of the program. Being Haskell it does so in a very mathematically pure way (called System F). The language of types (that is the rules by which types are deduced) are similar to Haskell itself.
Now remember Haskell is a lazy language. It doesn't work out the value of anything until it needs it. That's why it makes sense in Haskell to have infinite data structures. It never occurs to Haskell that a data structure is infinite because it doesn't bother to work it out until it needs to.
Now all that lazy magic happens at the type level too. In the same way that Haskell doesn't work out what the value of an expression is until it really needs to, Haskell doesn't work out what the type of an expression is until it really needs to.
Consider this function
func (x : y : rest) = (x,y) : func rest
func _ = []
If you ask Haskell for the type of this function it has a look at the definition, sees [] and : and deduces that it's working with lists. But it never needs to look at the types of x and y, it just knows that they have to be the same because they end up in the same list. So it deduces the type of the function as [a] -> [a] where a is a type that it hasn't bothered to work out yet.
So far no magic. But it's useful to notice the difference between this idea and how it would be done in an OO language. Haskell doesn't convert the arguments to Object, do it's thing and then convert back. Haskell just hasn't been asked explicitly what the type of the list is. So it doesn't care.
Now try typing the following into ghci
maxBound - length ""
maxBound : "Hello"
Now what just happened !? minBound bust be a Char because I put it on the front of a string and it must be an integer because I added it to 0 and got a number. Plus the two values are clearly very different.
So what is the type of minBound? Let's ask ghci!
:type minBound
minBound :: Bounded a => a
AAargh! what does that mean? Basically it means that it hasn't bothered to work out exactly what a is, but is has to be Bounded if you type :info Bounded you get three useful lines
class Bounded a where
minBound :: a
maxBound :: a
and a lot of less useful lines
So if a is Bounded there are values minBound and maxBound of type a.
In fact under the hood Bounded is just a value, it's "type" is a record with fields minBound and maxBound. Because it's a value Haskell doesn't look at it until it really needs to.
So I appear to have meandered somewhere in the region of the answer to your question. Before we move onto return (which you may have noticed from the comments is a wonderfully complex beast.) let's look at read.
ghci again
read "42" + 7
read "'H'" : "ello"
length (read "[1,2,3]")
and hopefully you won't be too surprised to find that there are definitions
read :: Read a => String -> a
class Read where
read :: String -> a
so Read a is just a record containing a single value which is a function String -> a. Its very tempting to assume that there is one read function which looks at a string, works out what type is contained in the string and returns that type. But it does the opposite. It completely ignores the string until it's needed. When the value is needed, Haskell first works out what type it's expecting, once it's done that it goes and gets the appropriate version of the read function and combines it with the string.
now consider something slightly more complex
readList :: Read a => [String] -> a
readList strs = map read strs
under the hood readList actually takes two arguments
readList' (Read a) -> [String] -> [a]
readList' {read = f} strs = map f strs
Again as Haskell is lazy it only bothers looking at the arguments when it's needs to find out the return value, at that point it knows what a is, so the compiler can go and fine the right version of Read. Until then it doesn't care.
Hopefully that's given you a bit of an idea of what's happening and why Haskell can "overload" on the return type. But it's important to remember it's not overloading in the conventional sense. Every function has only one definition. It's just that one of the arguments is a bag of functions. read_str doesn't ever know what types it's dealing with. It just knows it gets a function String -> a and some Strings, to do the application it just passes the arguments to map. map in turn doesn't even know it gets strings. When you get deeper into Haskell it becomes very important that functions don't know very much about the types they're dealing with.
Now let's look at return.
Remember how I said that the type system in Haskell was very similar to Haskell itself. Remember that in Haskell functions are just ordinary values.
Does this mean I can have a type that takes a type as an argument and returns another type? Of course it does!
You've seen some type functions Maybe takes a type a and returns another type which can either be Just a or Nothing. [] takes a type a and returns a list of as. Type functions in Haskell are usually containers. For example I could define a type function BinaryTree which stores a load of a's in a tree like structure. There are of course lots of much stranger ones.
So, if these type functions are similar to ordinary types I can have a typeclass that contains type functions. One such typeclass is Monad
class Monad m where
return a -> m a
(>>=) m a (a -> m b) -> m b
so here m is some type function. If I want to define Monad for m I need to define return and the scary looking operator below it (which is called bind)
As others have pointed out the return is a really misleading name for a fairly boring function. The team that designed Haskell have since realised their mistake and they're genuinely sorry about it. return is just an ordinary function that takes an argument and returns a Monad with that type in it. (You never asked what a Monad actually is so I'm not going to tell you)
Let's define Monad for m = Maybe!
First I need to define return. What should return x be? Remember I'm only allowed to define the function once, so I can't look at x because I don't know what type it is. I could always return Nothing, but that seems a waste of a perfectly good function. Let's define return x = Just x because that's literally the only other thing I can do.
What about the scary bind thing? what can we say about x >>= f? well x is a Maybe a of some unknown type a and f is a function that takes an a and returns a Maybe b. Somehow I need to combine these to get a Maybe b`
So I need to define Nothing >== f. I can't call f because it needs an argument of type a and I don't have a value of type a I don't even know what 'a' is. I've only got one choice which is to define
Nothing >== f = Nothing
What about Just x >>= f? Well I know x is of type a and f takes a as an argument, so I can set y = f a and deduce that y is of type b. Now I need to make a Maybe b and I've got a b so ...
Just x >>= f = Just (f x)
So I've got a Monad! what if m is List? well I can follow a similar sort of logic and define
return x = [x]
[] >>= f = []
(x : xs) >>= a = f x ++ (xs >>= f)
Hooray another Monad! It's a nice exercise to go through the steps and convince yourself that there's no other sensible way of defining this.
So what happens when I call return 1?
Nothing!
Haskell's Lazy remember. The thunk return 1 (technical term) just sits there until someone needs the value. As soon as Haskell needs the value it know what type the value should be. In particular it can deduce that m is List. Now that it knows that Haskell can find the instance of Monad for List. As soon as it does that it has access to the correct version of return.
So finally Haskell is ready To call return, which in this case returns [1]!
The return function is from the Monad class:
class Applicative m => Monad (m :: * -> *) where
...
return :: a -> m a
So return takes any value of type a and results in a value of type m a. The monad, m, as you've observed is polymorphic using the Haskell type class Monad for ad hoc polymorphism.
At this point you probably realize return is not an good, intuitive, name. It's not even a built in function or a statement like in many other languages. In fact a better-named and identically-operating function exists - pure. In almost all cases return = pure.
That is, the function return is the same as the function pure (from the Applicative class) - I often think to myself "this monadic value is purely the underlying a" and I try to use pure instead of return if there isn't already a convention in the codebase.
You can use return (or pure) for any type that is a class of Monad. This includes the Maybe monad to get a value of type Maybe a:
instance Monad Maybe where
...
return = pure -- which is from Applicative
...
instance Applicative Maybe where
pure = Just
Or for the list monad to get a value of [a]:
instance Applicative [] where
{-# INLINE pure #-}
pure x = [x]
Or, as a more complex example, Aeson's parse monad to get a value of type Parser a:
instance Applicative Parser where
pure a = Parser $ \_path _kf ks -> ks a

Haskell: type mismatch when chaining getPermissions and searchable?

I'm a bit of a newbie with haskell and am trying to understand why the following code seems to fail.
Why can I not write:
getPermissions "." >>= searchable
but I can write:
do { p <- getPermissions "."; return $ searchable p }
The former fails with the following error:
<interactive>:65:24:
Couldn't match type `Bool' with `IO b0'
Expected type: Permissions -> IO b0
Actual type: Permissions -> Bool
In the second argument of `(>>=)', namely `searchable'
In the expression: getPermissions "." >>= searchable
In an equation for `it': it = getPermissions "." >>= searchable
My understanding is that (>>=) operates similarly to (<-) effectively passing the unwrapped value in the monad to a non-monad function.
What am I not understanding correctly? And how could one chain/compose getPermissions and searchable together concisely?
Many thanks in advance for your assistance!
#Arjan's comment above helped me get a better sense of what's going on. And some additional exploration on my part seemed to solidify the solution.
As mentioned in my second comment above, I seem to have overlooked the return type of the function used in the rhs of the bind (>>=). Since searchable returns a Bool, it doesn't fully qualify as the rhs' type which needs to be some type wrapped in IO, per the error message I saw above (IO b0). By promoting searchable's Bool return type using return I satisfy >>='s rhs type.
#Arjan's code in his comment also gives a concise form I was looking for:
getPermissions "." >>= (return . searchable)
Many thanks!

What type is chosen for a polymorphic expression when printed?

What is the type of return "abc" when printed in ghci?
The point of the question is that it's polymorphic in the monad:
ghci> :t return "abc"
return "abc" :: (Monad m) => m [Char]
and what gets printed depends on which monad is chosen:
ghci> return "abc" :: Maybe String
Just "abc"
ghci> return "abc" :: [] String
["abc"]
but here's what's actually printed:
ghci> return "abc"
"abc"
When you type an expression expr into GHCi, the following things happen:
The expression is type-checked. If there is an error, GHCi tells you the error and gives up.
Otherwise, say expr is found to have type t; GHC tries to match t against IO a.
If it succeeds, then it executes something like it <- expr, then if a is an instance of Show and is not (), it executes print it.
If it fails, and t itself is an instance of Show, GHCi does something like let it = expr and then print it.
Otherwise, it complains.
Essentially, you need a way at the GHCi prompt both of running IO actions and getting at the values they return, and of playing around with pure values and seeing what you get. That's why GHCi behaves the way it does: if it seems like you're using an IO action, GHCi will do it, and then if that action has a result that can be shown and is interesting (i.e. not ()) then it shows the result to you. If it can't show the result to you, then it's no big deal, because you probably just wanted to run the IO action anyway; if you wanted the result you would have named it with <-. On the other hand, if it seems like your expression is not an IO action, GHCi calculates it and shows it to you, and if it can't be shown then GHCi can't do anything useful (no side-effects this time), so complains.
In this case, return "abc" typechecks as IO String, and String is an instance of Show, so GHCi does something like
it <- return "abc"
print it
which by the monad laws is exactly the same as just doing
print "abc"
hence the result.
Haskell has a slightly baffling set of rules for deciding the types of expressions involving numbers; you can see the Report section on ambiguous types and default instances. So the answer to the general question is complicated. But within GHCi, if you enter an expression e, you can rely on these rules to apply:
If the expression e can be typed as IO T for some type T, and if T has a Show instance, GHCi will run the computation and print the resulting value of type T. That's what's happening in your third example.
If the expression e *cannot* be typed in the IO monad, then the default-instance rules come into play, and GHCi will choose a type according to those rules. If the type has a Show instance GHCi will then print show e. That's what happens in your first two examples: Maybe String and [String] are pure values with Show instances.
If e's type does not have a Show instance, then GHCi will complain. That will happen if you type an expression like flip take.

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