Does there exist something like (xs:x) - haskell

I'm new to Haskell. I know I can create a reverse function by doing this:
reverse :: [a] -> [a]
reverse [] = []
reverse (x:xs) = (Main.reverse xs) ++ [x]
Is there such a thing as (xs:x) (a list concatenated with an element, i.e. x is the last element in the list) so that I put the last list element at the front of the list?
rotate :: [a] -> [a]
rotate [] = []
rotate (xs:x) = [x] ++ xs
I get these errors when I try to compile a program containing this function:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `rotate'

I'm also new to Haskell, so my answer is not authoritative. Anyway, I would do it using last and init:
Prelude> last [1..10] : init [1..10]
[10,1,2,3,4,5,6,7,8,9]
or
Prelude> [ last [1..10] ] ++ init [1..10]
[10,1,2,3,4,5,6,7,8,9]

The short answer is: this is not possible with pattern matching, you have to use a function.
The long answer is: it's not in standard Haskell, but it is if you are willing to use an extension called View Patterns, and also if you have no problem with your pattern matching eventually taking longer than constant time.
The reason is that pattern matching is based on how the structure is constructed in the first place. A list is an abstract type, which have the following structure:
data List a = Empty | Cons a (List a)
deriving (Show) -- this is just so you can print the List
When you declare a type like that you generate three objects: a type constructor List, and two data constructors: Empty and Cons. The type constructor takes types and turns them into other types, i.e., List takes a type a and creates another type List a. The data constructor works like a function that returns something of type List a. In this case you have:
Empty :: List a
representing an empty list and
Cons :: a -> List a -> List a
which takes a value of type a and a list and appends the value to the head of the list, returning another list. So you can build your lists like this:
empty = Empty -- similar to []
list1 = Cons 1 Empty -- similar to 1:[] = [1]
list2 = Cons 2 list1 -- similar to 2:(1:[]) = 2:[1] = [2,1]
This is more or less how lists work, but in the place of Empty you have [] and in the place of Cons you have (:). When you type something like [1,2,3] this is just syntactic sugar for 1:2:3:[] or Cons 1 (Cons 2 (Cons 3 Empty)).
When you do pattern matching, you are "de-constructing" the type. Having knowledge of how the type is structured allows you to uniquely disassemble it. Consider the function:
head :: List a -> a
head (Empty) = error " the empty list have no head"
head (Cons x xs) = x
What happens on the type matching is that the data constructor is matched to some structure you give. If it matches Empty, than you have an empty list. If if matches Const x xs then x must have type a and must be the head of the list and xs must have type List a and be the tail of the list, cause that's the type of the data constructor:
Cons :: a -> List a -> List a
If Cons x xs is of type List a than x must be a and xs must be List a. The same is true for (x:xs). If you look to the type of (:) in GHCi:
> :t (:)
(:) :: a -> [a] -> [a]
So, if (x:xs) is of type [a], x must be a and xs must be [a] . The error message you get when you try to do (xs:x) and then treat xs like a list, is exactly because of this. By your use of (:) the compiler infers that xs have type a, and by your use of
++, it infers that xs must be [a]. Then it freaks out cause there's no finite type a for which a = [a] - this is what he's trying to tell you with that error message.
If you need to disassemble the structure in other ways that don't match the way the data constructor builds the structure, than you have to write your own function. There are two functions in the standard library that do what you want: last returns the last element of a list, and init returns all-but-the-last elements of the list.
But note that pattern matching happens in constant time. To find out the head and the tail of a list, it doesn't matter how long the list is, you just have to look to the outermost data constructor. Finding the last element is O(N): you have to dig until you find the innermost Cons or the innermost (:), and this requires you to "peel" the structure N times, where N is the size of the list.
If you frequently have to look for the last element in long lists, you might consider if using a list is a good idea after all. You can go after Data.Sequence (constant time access to first and last elements), Data.Map (log(N) time access to any element if you know its key), Data.Array (constant time access to an element if you know its index), Data.Vector or other data structures that match your needs better than lists.
Ok. That was the short answer (:P). The long one you'll have to lookup a bit by yourself, but here's an intro.
You can have this working with a syntax very close to pattern matching by using view patterns. View Patterns are an extension that you can use by having this as the first line of your code:
{-# Language ViewPatterns #-}
The instructions of how to use it are here: http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns
With view patterns you could do something like:
view :: [a] -> (a, [a])
view xs = (last xs, init xs)
someFunction :: [a] -> ...
someFunction (view -> (x,xs)) = ...
than x and xs will be bound to the last and the init of the list you provide to someFunction. Syntactically it feels like pattern matching, but it is really just applying last and init to the given list.

If you're willing to use something different from plain lists, you could have a look at the Seq type in the containers package, as documented here. This has O(1) cons (element at the front) and snoc (element at the back), and allows pattern matching the element from the front and the back, through use of Views.

"Is there such a thing as (xs:x) (a list concatenated with an element, i.e. x is the last element in the list) so that I put the last list element at the front of the list?"
No, not in the sense that you mean. These "patterns" on the left-hand side of a function definition are a reflection of how a data structure is defined by the programmer and stored in memory. Haskell's built-in list implementation is a singly-linked list, ordered from the beginning - so the pattern available for function definitions reflects exactly that, exposing the very first element plus the rest of the list (or alternatively, the empty list).
For a list constructed in this way, the last element is not immediately available as one of the stored components of the list's top-most node. So instead of that value being present in pattern on the left-hand side of the function definition, it's calculated by the function body onthe right-hand side.
Of course, you can define new data structures, so if you want a new list that makes the last element available through pattern-matching, you could build that. But there's be some cost: Maybe you'd just be storing the list backwards, so that it's now the first element which is not available by pattern matching, and requires computation. Maybe you're storing both the first and last value in the structures, which would require additional storage space and bookkeeping.
It's perfectly reasonable to think about multiple implementations of a single data structure concept - to look forward a little bit, this is one use of Haskell's class/instance definitions.

Reversing as you suggested might be much less efficient. Last is not O(1) operation, but is O(N) and that mean that rotating as you suggested becomes O(N^2) alghorhim.
Source:
http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/GHC-List.html#last
Your first version has O(n) complexity. Well it is not, becuase ++ is also O(N) operation
you should do this like
rotate l = rev l []
where
rev [] a = a
rev (x:xs) a = rev xs (x:a)
source : http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/src/GHC-List.html#reverse

In your latter example, x is in fact a list. [x] becomes a list of lists, e.g. [[1,2], [3,4]].
(++) wants a list of the same type on both sides. When you are using it, you're doing [[a]] ++ [a] which is why the compiler is complaining. According to your code a would be the same type as [a], which is impossible.
In (x:xs), x is the first item of the list (the head) and xs is everything but the head, i.e., the tail. The names are irrelevant here, you might as well call them (head:tail).
If you really want to take the last item of the input list and put that in the front of the result list, you could do something like:
rotate :: [a] -> [a]
rotate [] = []
rotate lst = (last lst):(rotate $ init lst)
N.B. I haven't tested this code at all as I don't have a Haskell environment available at the moment.

Related

case-of / case expression with or in pattern matching possible?

I am learning haskell on my own. And was working on implementing a custom List data type using basic lists and case of.
So data structure is something similar to this
data List = List [String] | EmptyList deriving Show
now if I am doing case expressions for base case, I have to do two matchings. A simple example would be the size function
size :: List -> Int
size lst = case lst of
(List []) -> 0
EmptyList -> 0
(List (x:xs)) -> 1 + size (List xs)
Can't I do something like combining the two base cases of list being empty (List []) and EmptyList somehow to reduce redundancy?
size :: List -> Int
size lst = case lst of
(List []) | EmptyList -> 0
(List (x:xs)) -> 1 + size (List xs)
I have tried searching all over the net for this, but unfortunately wasn't able to find anything concrete over matching multiple patterns in one case.
First of all you should consider why you have separate constructors for List and EmptyList in the first place. The empty list clearly is already a special case of a list anyway, so this is an awkward redundancy. If anything, you should make it
import Data.List.NonEmpty
data List' a = NEList (NonEmpty a) | EmptyList
Another option that would work for this specific example is to make the empty case into a “catch-all pattern”:
size :: List -> Int
size lst = case lst of
(List (x:xs)) -> 1 + size (List xs)
_ -> 0
BTW there's no reason to use case here, you can also just write two function clauses:
size :: List -> Int
size (List (x:xs)) = 1 + size (List xs)
size _ = 0
Anyways – this is generally discouraged, because catch-all clauses are an easy place for hard to detect bugs to creep in if you extend your data type in the future.
Also possible, but even worse style is to use a boolean guard match – this can easily use lookups in a list of options, like
size lst | lst`elem`[EmptyList, List []] = 0
size (List (x:xs)) = 1 + size (List xs)
Equality checks should be avoided if possible; they introduce an Eq constraint which, quite needlessly, will require the elements to be equality-comparable. And often equality check is also more computationally expensive than a pattern match.
Another option if you can't change the data structure itself but would like to work with it as if List [] and EmptyList were the same thing would be to write custom pattern synonyms. This is a relatively recent feature of Haskell; it kind of pretends the data structure is actually different – like List' – from how it's really layed out.
In the comments, you say
there are no such functions [which should return different results for EmptyList and List []]
therefore I recommend merging these two constructors in the type itself:
data List = List [String] deriving Show
Now you no longer need to distinguish between EmptyList and List [] in functions that consume a List.
...in point of fact, I would go even further and elide the definition entirely, simply using [String] everywhere instead. There is one exception to this: if you need to define an instance for a class that differs in behavior from [String]'s existing instance. In that exceptional case, defining a new type is sensible; but I would use newtype instead of data, for the usual efficiency and semantics reasons.

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.

Why does Haskell let me return an empty list where a list inside a list is expected?

I'm really new to Haskell and have been going through the 99 problems translation. This is my solution to number 9:
pack :: (Eq a) => [a] -> [[a]]
pack (xs)
| null xs = []
| otherwise =
let (matched, unmatched) = span (== head xs) xs
in [matched] ++ pack unmatched
I don't get how I'm allowed to do | null xs = [] when the type signature says the function returns a [[]]. I've seen other solutions to the same problem do the same thing.
I mean, I'm not complaining, but is this something specifically allowed? Are there any caveats I have to look out for?
I'm using the GHCi on a default Windows 7 Haskell Platform 2013.2.0.0 installation, if that helps.
[] is an empty list. It has the following type:
[] :: [b] -- Note: I'm using b instead of a because your function already uses a
That b can be everything. Can you choose a b such that [b] ~ [[a]]? (~ is equality for types)? Yes, just use b ~ [a] and the type of [] becomes:
[] :: [b] :: [[a]] -- When b ~ [a]
So [] is also a value of type [[a]]. [] is a valid value for any type of list, be it a list of a's or a list of lists of a's.
[Integer] is the type meaning "a list of integer values". Can there be a value in this type that doesn't actually contain any integers? Yes, the empty list [] contains zero integers.
[[Integer]] is the type meaning "a list of lists of integer values". Can there be a value in this type that doesn't actually contain any lists? Yes, the empty list [] contains zero lists.
Note that [] with type [[Integer]] is quite different from [[]] with the same type. The first represents the empty list of lists. The second is a non-empty list; it contains exactly one element, which is itself the empty list. A box containing one empty box is not the same thing as a box containing nothing at all! We could of course have [[], [], [], []] as well, where the outer non-empty list contains several elements, each of which is a empty list.
If it helps, think of the type [[Integer]] as representing list of rows, where each row is a list of integers. For example, the following:
11, 12, 13;
21, 22, 23, 24;
31;
is one way of visualising the [[Integer]] value [[11, 12, 13], [21, 22, 23, 24], [31]], where I've used commas to separate elements of the inner lists, and also semicolons to terminate each row (also line breaks to make it easy to read).
In that scheme, [[]] is the list consisting of one empty row. so you'd write it as just a single line ending in a semicolon. Whereas [] is a list with no rows at all, not even empty ones. So you'd write it as a blank file with no semicolons.
If that helped, then it should be easy to see how that applies to more abstract types like [[a]]. In general tough, [] with some list type (regardless of what type is written between the brackets) is always the list consisting of zero of the element type; it doesn't matter whether the element type itself is a list (or anything else with a concept of "empty").
Because [] is of type [[a]] in this case: it is a list containing exactly 0 alpha lists.
In general, the empty list can match any list type because every element (all zero of them) is of the correct type.
You already have a lot of great examples, but this might be a useful way to think about it.
Consider a type isomorphic to Haskell's lists, but without the syntactic sugar:
data List a = Nil
| Cons a (List a)
Each type in Haskell is classified by its kind. This List type is of kind * -> *, which you can think of as a sort of type-level function that takes a basic type (of kind *) and returns another basic type.
You'll notice that the Cons constructor is also parameterized this way; it will be different for every different type a passed to the List type. But the Nil constructor is not parameterized that way; this means that the empty list constructor is the same for every type a that you may pass to List a. Nil remains polymorphic even when List a is constrained to a single type because its value does not depend on what a we choose!
So, the type of Nil is List a. This corresponds to [] in standard list notation. But how does [[]] translate to this desugared list type? The value is Cons Nil Nil and the type is List (List a)! In this syntax it is clearly not an empty list; it is a single-element list containing the empty list. It's still fully polymorphic, since nothing has yet constrained a to a single type, but it's definitely not empty.
The confusing thing about your example is that the name of the overall list type is the same as one of its constructors. If you see [[a]] in code you have to look at whether it's in a type context or a value context. In the former, it would mean (in our desugared notation) the type List (List a) while in the latter it would mean the value Cons (Cons a Nil) Nil.
This is not an answer, but may I suggest using pattern matches instead of head and null?
pack :: (Eq a) => [a] -> [[a]]
pack xs = case xs of
[] -> []
x:_ ->
let (matched, unmatched) = span (== x) xs
in [matched] ++ pack unmatched
This has the benefit the compiler will statically check that you don't access the first element of the list when the list is empty. Generally, use of head is considered non-idiomatic.
The following would be perhaps instructive: instead of
pack :: (Eq a) => [a] -> [[a]]
pack (xs)
| null xs = []
...
try to write it thus:
pack :: (Eq a) => [a] -> [[a]]
pack (xs)
| null xs = xs -- since xs is the empty list (WRONG!)
...
Based on the following (wrong) reasoning: We know that we must return the empty list when the argument is empty, hence, we can save typing [] (which would require pressing AltGr, for example on german keyboards) and return the argument right away -- it is the empty list, after all, as the null check confirmed.
The type checker will disagree, however, on this point.
As a matter of fact, for the typechecker there exist infinitely many different empty lists, each possible list element type has its own empty list. In most cases, however, the type checker will identify the correct one when you give him [] - after all, in our example it knows that it must be a list of lists of as from the type signature.

What does [a] stand for exactly?

I'm doing some exercises from "Real World Haskell". One is to design a safe version of init :: [a] -> [a].
I'm supposed to start from safeInit :: [a] -> Maybe [a]
This is what I have at the moment.
safeInit :: [a] -> Maybe [a]
safeInit [] = Nothing
safeInit [a] = if length [a] <= 1
then Nothing
else Just (take (length [a] -1) [a])
In GCHi, when testing safeInit [1,2] I get the error message
* Exception: ch4exercise.hs:(21,1)-(24,44): Non-exhaustive patterns in function safeInit
I was under the impression that [a] simply stands for a list (of any size) of a's. What am I doing wrong?
As a type, [a] does stand for "a list of any size of as". As a pattern however, [a] stands for "a list containing exactly one element, which shall henceforth be known by the name a". Similarly [a,b] would mean "a list containing two elements, the first of which shall be known as a and the second of which shall be known as b" and so. [], as you already seem to know, stands for "a list containing exactly 0 elements".
This is analogous to how you'd write list literals as expressions. I.e. if you write myList = [], myList is the empty list and if you write myList = [x], myList is a list containing exactly one element, which is the value of the variable x.
[] is the empty list, a list containing nothing.
[a] is a list containing exactly one element, and that element (not the list) will be identified as "a" in the function.
You therefore still need to consider the case where the list contains several elements.
If you just use "a" rather than "[a]", then "a" will refer to the whole list, and you can start taking it apart with the functions you have to hand.
Note that you've already dealt with the situation in which you have an empty list, so you shouldn't need to check it again in the if statement.
One thing you'll have to get used to in Haskell, which isn't very intuitive until you're reasonably experienced, is that the "namespace" for type-level things is completely separate from the namespace for value-level things. This means the same source text can have a completely different meaning when you're talking about types than when you're talking about values.
safeInit :: [a] -> Maybe [a]
Everything following the :: is talking about types. Here [a] is the list type constructor applied to the type variable a.1 So it's the type of lists (of any size) whose elements are of type a.
safeInit [a] = if length [a] <= 1
...
OTOH this equation is at the value level. Here [a] isn't a type, it's a value (on the left hand side of the = it's a pattern to be matched by the value to which safeInit was applied; on the right hand side it's just a value). At the value level the square bracket syntax isn't the list type constructor, it's syntactic sugar for writing lists, with all the elements of the lists separated by commas inside the brackets. So [a] is the value of a list containing one single element, which is denoted by the variable a. If we wanted the list to be empty we'd write []. If we wanted the list to contain just a and b we'd write [a, b], etc.
At the value level it wouldn't make much sense for [a] to be a list of any number of as, because (during any particular evaluation of this code) a is one particular value, such as 3.4. What use is an expression for a list of any number of 3.4s?
1 Just as Maybe a is the Maybe type constructor applied to the type variable a; the only thing that's special about the list type constructor is that it's called [] rather than a normal name, and gets this odd "surrounding" syntax for application rather than the usual prefix form.
There's a problem with this line:
safeInit [a] = if length [a] <= 1
On the left side of the equation, [a] will match a list with exactly one element. So the compiler sees that you have a version of safeInit for an empty list, a version of safeInit for a list with one element, but nothing for a list with more elements. That's why it's complaining about Non-exhaustive patterns.
I think that what you really want is
safeInit a = if length a <= 1
then Nothing
else Just (take (length a -1) a)
To summarise:
In a type signature, [a] stands for a list of elements of arbitrary type a.
In a pattern, [a] matches a list with exactly one element.

How do I implement a recursive list in Haskell and methods to operate on it

I'm attempting to create a method in Haskell which I would think is very intuitive. I have a list of lists [of lists]* that is arbitrarily deep. I'd like to pull out a specific atom in the list regardless of the depth of the recursion. Here's my effort:
type List = [Array]
data Array = Int | List
drill :: Array -> [Int] -> Array
drill xs (index:[]) = xs !! index
drill xs (index:is) = drill (xs !! index) is
However I receive the following when loading in ghci:
drill.hs:5:23:
Couldn't match expected type `[Array]' with actual type `Array'
In the first argument of `(!!)', namely `xs'
In the expression: xs !! index
In an equation for `drill': drill xs (index : []) = xs !! index
What I've written seems intuitive to me but clearly Haskell is having type issues. And as a Haskell newbie, I'm not the best at interpreting type errors. I would think that the return type of the function could be either an atom: Int, or a list:[Int]. Can anybody help me decipher this and suggest a solution?
When you say
data Array = Int | List
this doesn't mean "any Int is an Array, and any List is an Array". It instead means that Array has two constructors, Int and List, both of which take no arguments. The confusion arises from the fact that they have the same name as types; they're not related to the types beyond sharing a name. That is, your declaration is basically the same as
data Array = Foo | Bar
Instead, we need to give explicit constructor names for each alternative:
type List = [Array]
data Array = Elem Int | Nest List
drill :: Array -> [Int] -> Array
drill xs [] = xs
drill (Nest xs) (index:is) = drill (xs !! index) is
This means that Elem takes an Int and returns an Array, and Nest takes a List and returns an Array. We have to adjust the drill function to explicitly take the list of Arrays out of the Nest case.
The error you're getting is basically saying that you're trying to use xs as a list, but it's an Array. This is because you didn't pattern-match on it at all: just tried to use your argument (an Array) directly as a list.
Note that you'll still have to explicitly pattern-match on the result of drill to tell whether it's a single element or a nested list. There's no way to make a type whose values can literally be either integers or nested lists in Haskell; Haskell's unions are tagged (i.e. the constructors are explicit), and it has no subtyping.
For more information, I suggest reading this introduction to algebraic data types from Learn You a Haskell.

Resources