Haskell: type mismatch when chaining getPermissions and searchable? - haskell

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!

Related

How do we know the output `a` has the same value as input `a` in the type signature (a,b) -> a [duplicate]

New to Haskell so sorry if this is very basic
This example is taken from "Real World Haskell" -
ghci> :type fst
fst :: (a, b) -> a
They show the type of the fst function and then follow it with this paragraph...
"The result type of fst is a. We've already mentioned that parametric polymorphism makes the real type inaccessible: fst doesn't have enough information to construct a value of type a, nor can it turn an a into a b. So the only possible valid behaviour (omitting infinite loops or crashes) it can have is to return the first element of the pair."
I feel like I am missing the fundamental point of the paragraph, and perhaps something important about Haskell. Why couldn't the fst function return type b? Why couldn't it take the tuple as a param, but simply return an Int ( or any other type that is NOT a)? I don't understand why it MUST return type a?
Thanks
If it did any of those things, its type would change. What the quote is saying is that, given that we know fst is of type (a, b) -> a, we can make those deductions about it. If it had a different type, we would not be able to do so.
For instance, see that
snd :: (a, b) -> a
snd (x, y) = y
does not type-check, and so we know a value of type (a, b) -> a cannot behave like snd.
Parametricity is basically the fact that a polymorphic function of a certain type must obey certain laws by construction — i.e., there is no well-typed expression of that type that does not obey them. So, for it to be possible to prove things about fst with it, we must first know fst's type.
Note especially the word polymorphism there: we can't do the same kind of deductions about non-polymorphic types. For instance,
myFst :: (Int, String) -> Int
myFst (a, b) = a
type-checks, but so does
myFst :: (Int, String) -> Int
myFst (a, b) = 42
and even
myFst :: (Int, String) -> Int
myFst (a, b) = length b
Parametricity relies crucially on the fact that a polymorphic function can't "look" at the types it is called with. So the only value of type a that fst knows about is the one it's given: the first element of the tuple.
The point is that once you have that type, the implementation options are greatly limited. If you returned an Int, then your type would be (a,b) -> Int. Since a could be anything, we can't gin one up out of thin air in the implementation without resorting to undefined, and so must return the one given to us by the caller.
You should read the Theorems for Free article.
Let's try to add some more hand-waving to that already given by Real World Haskell. Lets try to convince ourselves that given that we have a function fst with type (a,b) -> a the only total function it can be is the following one:
fst (x,y) = x
First of all, we cannot return anything other then a value of type a, that is in the premise that fst has type (a,b) -> a, so we cannot have fst (x,y) = y or fst (x,y) = 1 because that does not have the correct type.
Now, as RWH says, if I give fst an (Int,Int), fst doesn't know these are Ints, furthermore, a or b are not required to belong to any type class so fst has no available values or functions associated with a or b.
So fst only knows about the a value and the b value that I give it and I can't turn b into an a (It can't make a b -> a function) so it must return the given a value.
This isn't actually just magical hand waving, one can actually deduce what possible expressions there are of a given polymorphic type. There is actually a program called djinn that does exactly that.
The point here is that both a and b are type variables (that might be the same, but that's not needed). Anyway, since for a given tuple of two elements, fst returns always the first element, the returned type must be always the same as the type for the first element.
The fundamental thing you're probably missing is this:
In most programming languages, if you say "this function returns any type", it means that the function can decide what type of value it actually returns.
In Haskell, if you say "this function returns any type", it means that the caller gets to decide what type that should be. (!)
So if I you write foo :: Int -> x, it can't just return a String, because I might not ask it for a String. I might ask for a Customer, or a ThreadId, or anything.
Obviously, there's no way that foo can know how to create a value of every possible type, even types that don't exist yet. In short, it is impossible to write foo. Everything you try will give you type errors, and won't compile.
(Caveat: There is a way to do it. foo could loop forever, or throw an exception. But it cannot return a valid value.)
There's no way for a function to be able to create values of any possible type. But it's perfectly possible for a function to move data around without caring what type it is. Therefore, if you see a function that accepts any kind of data, the only thing it can be doing with it is to move it around.
Alternatively, if the type has to belong to a specific class, then the function can use the methods of that class on it. (Could. It doesn't have to, but it can if it wants to.)
Fundamentally, this is why you can actually tell what a function does just by looking at its type signature. The type signature tells you what the function "knows" about the data it's going to be given, and hence what possible operations it might perform. This is why searching for a Haskell function by its type signature is so damned useful.
You've heard the expression "in Haskell, if it compiles, it usually works right"? Well, this is why. ;-)

Haskell Return Doesn't Match Expected

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!

Can't compile because of types when using nub, map and take

I've got this simple function:
bombplaces::Int->[(Int,Int)]->[(Int,Int)]
bombplaces bombCount listOfPossiblePoints = nub (map (take bombCount) (perms listOfPossiblePoints))
bombs are (x,y) (carthesian points)
i need to get an all permutations and take only first few (bombCount) points.
I'm getting following error:
Couldn't match expected type `(Int,Int)' with actual type `[a0]'
Expected type: [a0] -> (Int,Int)
Actual type: [a0] -> [a0]
In the return type of a call of `take'
In the first argument of `map', namely `(take liczbaBomb)'
If you remove the type signature and ask GHCi for the type, your problem will be obvious:
> :t bombplaces
bombplaces :: Eq a => Int -> [a] -> [[a]]
That is, bombplaces wants to return a list of lists whereas you want it to return a plain list. You need to either change the type signature, or change the definition of the function, depending on what you want the behaviour to be.
N.B. You didn't tell us what definition of perms you are using, so I assumed the obvious one.

determining function behavior from the type of the function

New to Haskell so sorry if this is very basic
This example is taken from "Real World Haskell" -
ghci> :type fst
fst :: (a, b) -> a
They show the type of the fst function and then follow it with this paragraph...
"The result type of fst is a. We've already mentioned that parametric polymorphism makes the real type inaccessible: fst doesn't have enough information to construct a value of type a, nor can it turn an a into a b. So the only possible valid behaviour (omitting infinite loops or crashes) it can have is to return the first element of the pair."
I feel like I am missing the fundamental point of the paragraph, and perhaps something important about Haskell. Why couldn't the fst function return type b? Why couldn't it take the tuple as a param, but simply return an Int ( or any other type that is NOT a)? I don't understand why it MUST return type a?
Thanks
If it did any of those things, its type would change. What the quote is saying is that, given that we know fst is of type (a, b) -> a, we can make those deductions about it. If it had a different type, we would not be able to do so.
For instance, see that
snd :: (a, b) -> a
snd (x, y) = y
does not type-check, and so we know a value of type (a, b) -> a cannot behave like snd.
Parametricity is basically the fact that a polymorphic function of a certain type must obey certain laws by construction — i.e., there is no well-typed expression of that type that does not obey them. So, for it to be possible to prove things about fst with it, we must first know fst's type.
Note especially the word polymorphism there: we can't do the same kind of deductions about non-polymorphic types. For instance,
myFst :: (Int, String) -> Int
myFst (a, b) = a
type-checks, but so does
myFst :: (Int, String) -> Int
myFst (a, b) = 42
and even
myFst :: (Int, String) -> Int
myFst (a, b) = length b
Parametricity relies crucially on the fact that a polymorphic function can't "look" at the types it is called with. So the only value of type a that fst knows about is the one it's given: the first element of the tuple.
The point is that once you have that type, the implementation options are greatly limited. If you returned an Int, then your type would be (a,b) -> Int. Since a could be anything, we can't gin one up out of thin air in the implementation without resorting to undefined, and so must return the one given to us by the caller.
You should read the Theorems for Free article.
Let's try to add some more hand-waving to that already given by Real World Haskell. Lets try to convince ourselves that given that we have a function fst with type (a,b) -> a the only total function it can be is the following one:
fst (x,y) = x
First of all, we cannot return anything other then a value of type a, that is in the premise that fst has type (a,b) -> a, so we cannot have fst (x,y) = y or fst (x,y) = 1 because that does not have the correct type.
Now, as RWH says, if I give fst an (Int,Int), fst doesn't know these are Ints, furthermore, a or b are not required to belong to any type class so fst has no available values or functions associated with a or b.
So fst only knows about the a value and the b value that I give it and I can't turn b into an a (It can't make a b -> a function) so it must return the given a value.
This isn't actually just magical hand waving, one can actually deduce what possible expressions there are of a given polymorphic type. There is actually a program called djinn that does exactly that.
The point here is that both a and b are type variables (that might be the same, but that's not needed). Anyway, since for a given tuple of two elements, fst returns always the first element, the returned type must be always the same as the type for the first element.
The fundamental thing you're probably missing is this:
In most programming languages, if you say "this function returns any type", it means that the function can decide what type of value it actually returns.
In Haskell, if you say "this function returns any type", it means that the caller gets to decide what type that should be. (!)
So if I you write foo :: Int -> x, it can't just return a String, because I might not ask it for a String. I might ask for a Customer, or a ThreadId, or anything.
Obviously, there's no way that foo can know how to create a value of every possible type, even types that don't exist yet. In short, it is impossible to write foo. Everything you try will give you type errors, and won't compile.
(Caveat: There is a way to do it. foo could loop forever, or throw an exception. But it cannot return a valid value.)
There's no way for a function to be able to create values of any possible type. But it's perfectly possible for a function to move data around without caring what type it is. Therefore, if you see a function that accepts any kind of data, the only thing it can be doing with it is to move it around.
Alternatively, if the type has to belong to a specific class, then the function can use the methods of that class on it. (Could. It doesn't have to, but it can if it wants to.)
Fundamentally, this is why you can actually tell what a function does just by looking at its type signature. The type signature tells you what the function "knows" about the data it's going to be given, and hence what possible operations it might perform. This is why searching for a Haskell function by its type signature is so damned useful.
You've heard the expression "in Haskell, if it compiles, it usually works right"? Well, this is why. ;-)

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

Resources