Haskell 'Couldn't match expected type with actual type' - haskell

I have been going through the Seven Languages in Seven Weeks book and I'm working with Haskell.
I am struggling with the problem:
Write a sort that takes a list and a function that compares its two arguments and then returns a sorted list.
I searched online for help and found a solution but I can't even get the solution to run because of an expected to actual type error.
Here is the code I've been trying:
module Main where
import Data.List
sortList :: (Ord a) => (a -> a -> Ordering) -> [a] -> [a]
sortList comparator list = sortBy comparator list
Here is the error:
*Main> sortList [5,4,2,7,8,1]
<interactive>:1:10:
Couldn't match expected type `a -> a -> Ordering'
with actual type `[t]'
In the first argument of `sortList', namely `[5, 4, 2, 7, ....]'
In the expression: sortList [5, 4, 2, 7, ....]
In an equation for `it': it = sortList [5, 4, 2, ....]
My Thoughts and Attempts:
Maybe I am calling the function wrong? I am fairly new to Haskell. II tried doing many searches as well. All I could conclude is that somewhere the types aren't matching up. I suppose explanation and guidance for the script would be very helpful to me.

Your function signature says:
"sortList is a function that takes:"
function (a -> a -> Ordering) that take two elements of type 'a' and returns an 'Ordering' [this is your comparator]
List of items 'a' ([a]) that you are passing it
Returns a list of items 'a' ([a])
Try call them in this way:
sortList compare [3,2,1]
For more read here:
https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Ord.html
and here:
http://zvon.org/other/haskell/Outputprelude/compare_f.html

You are calling the function wrong, you need to pass it a comparator function. You just pass a list to the function.

Related

Head function throwing type match errors Haskell

So basically i'm taking a list of items and adding to a list of tuples to make it more efficient way to store/view the data. My code is
TList :: [a] -> a -> [(a,Int)] -> [(a,Int)]
TList head [a] [] = [(head [a],1)]
TList head [a] ((a',i):xa)
|a' == take 1 = (head 1,i+1):xa
|otherwise = (a',i) : TList drop 1 [a] xa
so my logic is that I take the first item in the list, checks to see if its already in the tuple list, if it is add one to the int. the call the function again but without the first list item
but it keeps giving the error
Couldn't match expected type '[t1] -> a' with actual type '[a]'
it gives this error 5 times, one for each line.
So, this is not a full answer to your question because I'm not sure what exactly you're trying to achieve. But there's a few things wrong with the code and I suggest you start by fixing them and then seeing how it goes:
Function names need to begin with a lower-case letter. Therefore, TList is not a legal name for a function. (Types and type constructors have upper case names). So maybe you want tList?
You are naming one of the parameters head. But head is also a Prelude function and you actually seem to use the head function (head [a]). But your parameter head will shadow the head function. Also head seems like an odd name for a proper list.
head [a] seems odd as head [a] == a. So the head of a list with just one element is always just that element.
I'm guessing you're trying to use drop 1 [a] (if so, you're missing parenthesis). That's odd too because drop 1 [a] == []. drop 1 of a list with just one element is always the empty list.
You're pattern matching the second parameter (type a) with [a] and that can't work because [a] only works with list types [t].
a' == take 1 doesn't really make sense. take 1 needs a list as the second argument take 1 [1, 2, 3] = [1]. So you're comparing something (a) of type a with another thing of type [a] -> [a] (take 1 :: [a] -> [a]).
When you wrote:
TList head [a] [] = ...
You've shadowed the original head function. Thus in this context:
[(head [a],1)]
It tries to evaluate it. I've no idea why haven'y you just used a here, the code is very unclear and it won't compile with that name (uppercase TList), but this is the source of this type mismatch.

Variable scope in a higher-order lambda function

In working through a solution to the 8 Queens problem, a person used the following line of code:
sameDiag try qs = any (\(colDist,q) -> abs (try - q) == colDist) $ zip [1..] qs
try is an an item; qs is a list of the same items.
Can someone explain how colDist and q in the lambda function get bound to anything?
How did try and q used in the body of lambda function find their way into the same scope?
To the degree this is a Haskell idiom, what problem does this design approach help solve?
The function any is a higher-order function that takes 2 arguments:
the 1st argument is of type a -> Bool, i.e. a function from a to Bool
the 2nd argument is of type [a], i.e. a list of items of type a;
i.e. the 1st argument is a function that takes any element from the list passed as the 2nd argument, and returns a Bool based on that element. (well it can take any values of type a, not just the ones in that list, but it's quite obviously certain that any won't be invoking it with some arbitrary values of a but the ones from the list.)
You can then simplify thinking about the original snippet by doing a slight refactoring:
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f = (\(colDist, q) -> abs (try - q) == colDist)
which can be transformed into
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f (colDist, q) = abs (try - q) == colDist)
which in turn can be transformed into
sameDiag :: Int -> [Int] -> Bool
sameDiag try qs = any f xs
where
xs = zip [1..] qs
f pair = abs (try - q) == colDist) where (colDist, q) = pair
(Note that sameDiag could also have a more general type Integral a => a -> [a] -> Bool rather than the current monomorphic one)
— so how does the pair in f pair = ... get bound to a value? well, simple: it's just a function; whoever calls it must pass along a value for the pair argument. — when calling any with the first argument set to f, it's the invocation of the function any who's doing the calling of f, with individual elements of the list xs passed in as values of the argument pair.
and, since the contents of xs is a list of pairs, it's OK to pass an individual pair from this list to f as f expects it to be just that.
EDIT: a further explanation of any to address the asker's comment:
Is this a fair synthesis? This approach to designing a higher-order function allows the invoking code to change how f behaves AND invoke the higher-order function with a list that requires additional processing prior to being used to invoke f for every element in the list. Encapsulating the list processing (in this case with zip) seems the right thing to do, but is the intent of this additional processing really clear in the original one-liner above?
There's really no additional processing done by any prior to invoking f. There is just very minimalistic bookkeeping in addition to simply iterating through the passed in list xs: invoking f on the elements during the iteration, and immediately breaking the iteration and returning True the first time f returns True for any list element.
Most of the behavior of any is "implicit" though in that it's taken care of by Haskell's lazy evaluation, basic language semantics as well as existing functions, which any is composed of (well at least my version of it below, any' — I haven't taken a look at the built-in Prelude version of any yet but I'm sure it's not much different; just probably more heavily optimised).
In fact, any is simple it's almost trivial to re-implement it with a one liner on a GHCi prompt:
Prelude> let any' f xs = or (map f xs)
let's see now what GHC computes as its type:
Prelude> :t any'
any' :: (a -> Bool) -> [a] -> Bool
— same as the built-in any. So let's give it some trial runs:
Prelude> any' odd [1, 2, 3] -- any odd values in the list?
True
Prelude> any' even [1, 3] -- any even ones?
False
Prelude> let adult = (>=18)
Prelude> any' adult [17, 17, 16, 15, 17, 18]
— see how you can sometimes write code that almost looks like English with higher-order functions?
zip :: [a] -> [b] -> [(a,b)] takes two lists and joins them into pairs, dropping any remaining at the end.
any :: (a -> Bool) -> [a] -> Bool takes a function and a list of as and then returns True if any of the values returned true or not.
So colDist and q are the first and second elements of the pairs in the list made by zip [1..] qs, and they are bound when they are applied to the pair by any.
q is only bound within the body of the lambda function - this is the same as with lambda calculus. Since try was bound before in the function definition, it is still available in this inner scope. If you think of lambda calculus, the term \x.\y.x+y makes sense, despite the x and the y being bound at different times.
As for the design approach, this approach is much cleaner than trying to iterate or recurse through the list manually. It seems quite clear in its intentions to me (with respect to the larger codebase it comes from).

Haskell - defining functions

I am new to programming and to Haskell. I'm having trouble understanding how to define a function. Let's say I want a function that will return element in position a of a list [b]. For a specific a and [b] I can do this in the interpreter:
Prelude> [2, 3, 5, 6] !! 1
Prelude> 3
But I run into trouble if I try to make a function, either in the interpreter or in a text editor that is then loaded:
Prelude> let getElement a [b] = [b] !! a
Prelude> getElement 1 [2, 3, 5, 6]
***Exception: <interactive>:17:5-27: Non-exhaustive pattern in function getElement
let getElement a [b] = [b] !! a
Your function takes one argument a of type Int, since (!!) second parameter is an Int, and [b] pattern matches on a list with one element.
It looks like you were trying to tell the complier that the second parameter should be a list. To do this you normally use the type signature.
In a file:
getElement :: Int -> [b] -> b
getElement a bs = bs !! a
This type of function is considered partial since you can give it an integer that causes the function to fail and throw an exception, such as a negative number or trying to access an index larger then the list. This chapter in real world Haskell has some information on partial function. The Haskell wiki in on the programming guidelines page has some advise too.
You may want to look at the
safe package and how they define headMay for a total, rather then partial, implementation.
Edit: b changed to bs as recommend by Rein Henrichs below, as he points out it does make it easier to read and is a rather common idiom.

A list of list or a tuple of tuples

I was just wondering if there is a possibility to create a function that returns an (hopefully infinite) list of numbers similar to this. [1, [2, [3, [4]]]].
The closest I got was this.
func list 0 = list
func list num = func newList (num-1)
where newList = list ++ [[num]]
This is used something like this.
func [] 3
Which returns this.
[[3],[2],[1]]
Now I know that this is not infinite nor is it in the correct order but I just wanted to show that I was at least attempting something before posting. :)
Thanks a bunch!
You cannot write such a function, because all elements of a list must have the same type. The list you want to create would not typecheck even in the case of just two elements:
Prelude> :t [1::Int,[2::Int]]
<interactive>:1:9:
Couldn't match expected type `Int' with actual type `[Int]'
In the expression: [2 :: Int]
In the expression: [1 :: Int, [2 :: Int]]
First element is a Int, second one a list of Int, hence typechecking fails.
Although you can express the result with tuples, e.g.
Prelude> :t (1::Int,(2::Int,(3::Int,4::Int)))
(1::Int,(2::Int,(3::Int,4::Int))) :: (Int, (Int, (Int, Int)))
You still cannot write the function, because the type of the result would change depending on the number of elements you wish to have. Let's call f the hypothetical function:
f 1 :: (Int)
f 2 :: (Int,(Int))
f 3 :: (Int,(Int,(Int)))
...
The type of f changes with the argument, so f cannot be written.
The key is to come up with the correct type.
If you want something like [1, [2, [3, [4]]]], then doing exactly that won't work, because all list elements must be the same type.
This makes sense, because when I grab an element out of the list, I need to know what type it is before I can do anything with it (this is sort of the whole point of types, they tell you what you can and can't do with a thing).
But since Haskell's type system is static, I need to know what type it is even without knowing which element of the list it is, because which list index I'm grabbing might not be known until the program runs. So I pretty much have to get the same type of thing whatever index I use.
However, it's possible to do something very much like what you want: you want a data type that might be an integer, or might be a list:
type IntegerOrList a = Either Integer [a]
If you're not familiar with the Either type, a value of Either l r can either be Left x for some x :: l, or Right y for some y :: r. So IntegerOrList a is a type whose values are either an integer or a list of something. So we can make a list of those things: the following is a value of type [IntegerOrList Bool]:
[Left 7, Left 4, Right [True, False], Left 8, Right [], Right [False]]
Okay, so that's one level of lists inside lists, but we can't put lists inside lists inside lists yet – the inner lists contain Bools, which can't be lists. If we instead had [IntegerOrList (IntegerOrList Bool)], we'd be able to have lists inside lists inside lists, but we'd still get no further. In our example, we had a list which contained values which were either integers or lists, and the lists were lists which contained values which were either integers or lists, and... what we really want is something like IntegerOrList (IntegerOrList (IntegerOrList ..., or more simply, something like:
type IntegerOrLists = Either Integer [IntegerOrLists]
But that's not allowed – type synonyms can't be recursive, because that would produce an infinitely large type, which is confusing for the poor compiler. However, proper data types can be recursive:
data IntegerOrLists = I Integer | L [IntegerOrLists]
Now you can build lists like these, mixing integers and lists of your type:
L [I 1, L [I 2, L [I 3, L [I 4]]]]
The key is that whether each item is an integer or a list has to be flagged by using the I or L constructors. Now each element of the list is of type IntegerOrLists, and we can distinguish which it is by looking at that constructor. So the typechecker is happy at last.
{-# LANGUAGE ExistentialQuantification #-}
class Foo a
instance Foo Int
instance Foo [a]
data F = forall a. Foo a => F a
test = F [F (1 :: Int), F [F (2 :: Int), F [F (3 :: Int), F [F (4 :: Int)]]]]
This example shows
That you can have such structures in Haskell, just use some gift wrapping
That these structures are practically useless (try to do something with it)

How do I determine the type of constant expressions in Haskell?

I am trying to revise for my functional programming exam, and am stumped on the first questions on past papers, and yes, we arent allowed solution sheets, here is an example of the 1st question on a past paper.
For each of the following expressions give its type in Haskell (for an expression that has many types, just give one type).
(True, "hello", 42)
[42, 4, 2]
length [True]
filter even
I think personally that the answer for one and two would be a tuple of bool, String and int and a list of ints respectively, is this correct to assume? and secondly how would you answer 3 and 4, i am sure length True just outputs a list of all elements that are of that length, and that filter even just alters a list of ints to a list that are of all even numbers, though how could i show this as an answer?
If you want to get types of variables offline with ghci you have to type
:t expression
if you want to create variables in ghci, you have to use let without using 'in' (as in do notation for monads, I don't know if you have seen them yet) :
let var = expr
If you check it all by yourself, you should be able to remember it more easily for your exams. (good luck for it ;))
length [True] will be Int, and it would return 1. You can check that with ghci or lambdabot.
filter even will be (Integral a) => [a] -> [a]
for example, [Int] -> [Int]
And I think this is kind of pointless because lambdabot can tell all those things to you.
To be precise, the type of [42, 4, 2] is going to be
Num a => [a]
This is because an integer literal in Haskell is treated as having an implicit "fromIntegral" in front of it, so the real expression is [fromIntegral 42, fromIntegral 4, fromIntegral 2].
"fromIntegral" is part of the Num class, and has the type
fromIntegral :: (Integral a, Num b) => a -> b
This says that it converts an instance of some Integral type (i.e. Int or Integer) into an arbitrary other numeric type (Int, Float, Double, Complex ...). This is why you can say something like "43.2 + 1" without getting a type error.
"length [True]" is going to have type Int, because "length" has type "[a] -> Int", and the argument (a list of Bool) is provided.
"filter even" is a little bit more complicated. Start with the type of "filter":
filter :: (a -> Bool) -> [a] -> [a]
The first parameter (the bit in brackets) is itself a function that takes a list item and returns a Bool. Remember that the "->" operator in Haskell types is right associative, so if you put in the implied brackets you see that the type is:
filter :: (a -> Bool) -> ([a] -> [a])
In other words if you give it the first argument, you get back a new function that expects the second argument. In this case the first argument is:
even :: (Integral a) => a -> Bool
This introduces a slight wrinkle: "even" requires its argument to be an Integral type (i.e. Int or Integer, as above), so this constraint has to be propagated to the result. If it were not then you could write this:
filter even "foo"
Hence the answer is:
filter even :: (Integral a) => [a] -> [a]
You can see that the Integral constraint comes from the type of "even", while the rest of the type comes from "filter".

Resources