This question already has answers here:
What does the : infix operator do in Haskell?
(4 answers)
Closed 8 years ago.
I've tried looking it up in hoogle and other various haskell dictionaries, but I can't find it. I was under the impression that it prepends, but I'm starting to see it in ways I haven't before and I've started second guessing myself.
For example, this is one of the questions that I don't understand:
(3 points) Fill in the blank with a pattern such that fun1 [(5,6),(7,8)] returns
5 and fun1 [(10,20),(30,40),(50,60)] returns 10:
and the answer is apparently:
((y,_):_)
fun1 _____________ = y
But I am so confused by this. I understand that the underscores mean that you don't really care about what the types of those are, but I don't understand what the (:) does in this answer.
While the other answers correctly explain what : is they don't quite answer the question - in the answer you have in your question : isn't used as a function, but as a constructor to pattern match on. fun (x:xs) = x means "if the argument is of the format (x:xs) give me the x". Pattern matching is used to "pull apart" complex types based on their constructors in Haskell.
In particular, since : is a list constructor you can pull apart lists with :
(conceptually list is defined as data [] a = [] | (:) a [a], although you're not gonna get this to compile because it's builtin syntax).
A non list example: We could define a datatype data F a b = A a | B b. This would create a type F that's parameterized with two types a and b and two constructors A and B with the types a -> F a b and b -> F a b respectively.
You could then write functions that use pattern matching to get at the contained values, like
isA (A _) = True -- this value was constructed with A, so it is an A
isA (B _) = False -- this value was constructed with B so it is not an A
or
getA (A a) = a -- this value was constructed with A so we can get an a out of it
getA (B _) = undefined -- ohps! We can't get an a back here cause we don't have one!
It is a List constructor function. It is used for prepending any value in front of the list.
ghci> 2 : [3,4]
[2,3,4]
It is just another Haskell function. You can also see it's type in ghci:
ghci> :t (:)
(:) :: a -> [a] -> [a]
Regarding your question, the answer is like this ((y,_):_) because it is being used in pattern matching. The first _ is the second element of the pair and the second _ pattern matches a list.
This may help you:
ghci> (5,6):[(7,8)]
[(5,6),(7,8)]
: is the list constructor of type a -> [a] -> [a]. It is usually used infix. but you can use it as prefix if you surround it with parentheses as you did. Just like any infix operation. (E.g. (+) 4 5 == 4 + 5)
So (:) a as is the same as a:as
Every constructor in Haskell can be also used do deconstruct a value of the type if constructs in a pattern match:
f x:xs = xs
would for example define a function that takes a non empty list and returns the tail. It would fail on an empty list because the empty list is constructed by the nullary constructor []. You could make f total by adding that second constructor to the match.
f [] = []
I guess your confusion comes from the fact that in haskell there is syntactic sugar that allows you to write lists in a more convenient way. Instead of (1:(2:(3:[]))) you can write [1,2,3] which is expanded into the former by the compiler.
In addition to the answers of what (:) function does, please, bear in mind that in the context of your question : is used as a deconstructor.
It is better to view (:) as a constructor. Then, just like any other data constructor, it can be used to introspect the contents of the value. Examples are:
f (Just x) = x -- extracts the value wrapped into Maybe a
f (x:_) = x -- extracts the value wrapped into a list, [a]
f ((x,_):_) = x -- extracts the value wrapped into a tuple in the list of tuples
In all these cases Just, : and (,) are constructors. The same syntax can be used to construct or deconstruct the values - depending on the context of the expression. Compare:
f x = Just x -- wraps x into Maybe a
f x xs = x:xs -- wraps x into a list, [a]
f x y z = (x,y):z -- wraps x into a tuple in the list of tuples
To understand what fun1 does, let's first look at another function:
f (x:xs) = x
If you pass this function a list such as [5,12,33], it will match x to 5, and xs to [12,33]. The function just returns x, i.e. the first element. So this function is basically the same as head. Since we don't actually use the value xs, we can rewrite the function as:
f (x:_) = x
Now let's look at fun1, but a slightly modified version.
fun1 ((y,z):xs) = y
If we pass this function the list [(5,6),(7,8)], it will match (y,z) to the pair (5,6) and xs to [(7,8)]. So now y is 5, and that's the value we return. Again, since we don't use z or xs, we can write the function as:
fun1 ((y,_):_) = y
Related
Doing the third of the 99-Haskell problems (I am currently trying to learn the language) I tried to incorporate pattern matching as well as recursion into my function which now looks like this:
myElementAt :: [a] -> Int -> a
myElementAt (x ++ xs) i =
if length (x ++ xs) == i && length xs == 1 then xs!!0
else myElementAt x i
Which gives me Parse error in pattern: x ++ xs. The questions:
Why does this give me a parse error? Is it because Haskell is no idea where to cut my list (Which is my best guess)?
How could I reframe my function so that it works? The algorithmic idea is to check wether the list has the length as the specified inde; if yes return the last elemen; if not cut away one element at the end of the list and then do the recursion.
Note: I know that this is a really bad algorithm, but it I've set myself the challenge to write that function including recursion and pattern matching. I also tried not to use the !! operator, but that is fine for me since the only thing it really does (or should do if it compiled) is to convert a one-element list into that element.
Haskell has two different kinds of value-level entities: variables (this also includes functions, infix operators like ++ etc.) and constructors. Both can be used in expressions, but only constructors can also be used in patterns.
In either case, it's easy to tell whether you're dealing with a variable or constructor: a constructor always starts with an uppercase letter (e.g. Nothing, True or StateT) or, if it's an infix, with a colon (:, :+). Everything else is a variable. Fundamentally, the difference is that a constructor is always a unique, immediately matcheable value from a predefined collection (namely, the alternatives of a data definition), whereas a variable can just have any value, and often it's in principle not possible to uniquely distinguish different variables, in particular if they have a function type.
Yours is actually a good example for this: for the pattern match x ++ xs to make sense, there would have to be one unique way in which the input list could be written in the form x ++ xs. Well, but for, say [0,1,2,3], there are multiple different ways in which this can be done:
[] ++[0,1,2,3]
[0] ++ [1,2,3]
[0,1] ++ [2,3]
[0,1,2] ++ [3]
[0,1,2,3]++ []
Which one should the runtime choose?
Presumably, you're trying to match the head and tail part of a list. Let's step through it:
myElementAt (x:_) 0 = x
This means that if the head is x, the tail is something, and the index is 0, return the head. Note that your x ++ x is a concatenation of two lists, not the head and tail parts.
Then you can have
myElementAt(_:tl) i = myElementAt tl (i - 1)
which means that if the previous pattern was not matched, ignore the head, and take the i - 1 element of the tail.
In patterns, you can only use constructors like : and []. The append operator (++) is a non-constructor function.
So, try something like:
myElementAt :: [a] -> Int -> a
myElementAt (x:xs) i = ...
There are more issues in your code, but at least this fixes your first problem.
in standard Haskell pattern matches like this :
f :: Int -> Int
f (g n 1) = n
g :: Int -> Int -> Int
g a b = a+b
Are illegal because function calls aren't allowed in patterns, your case is just a special case as the operator ++ is just a function.
To pattern match on lists you can do it like this:
myElementAt :: [a] -> Int -> a
myElementAt (x:xs) i = // result
But in this case x is of type a not [a] , it is the head of the list and xs is its tail, you'll need to change your function implementation to accommodate this fact, also this function will fail with the empty list []. However that's the idiomatic haskell way to pattern match aginst lists.
I should mention that when I said "illegal" I meant in standard Haskell, there are GHC extensions that give something similar to that , it's called ViewPatterns But I don't think you need it especially that you're still learning.
I want to get the first element of every tuple stored in a list like so:
INPUT : [(1,2,3), (1,4,5), (1,6,7)]
Wanted OUTPUT : [(1,1,1)] % Note the tuple notation
This is the function I have written so far:
f [] = []
f ((x,y,z):xs) = x:(f xs)
But it gives me this output:
[1,1,1]
instead of
[(1,1,1)]
Where is my misunderstanding?
As yet stated in the comment by #pdexter, you cannot create a tuple with arbitrary length. So what you're trying to do will only work when the tuple exactly pattern matches a tuple with 3 Ints. Let me show you an example to clarify what I mean:
helper :: [(Int,Int,Int)] -> (Int,Int,Int)
helper xs = (x,y,z)
where [x,y,z] = f xs
f :: [(Int,Int,Int)] -> [Int]
f [] = []
f ((x,y,z):xs) = x : (f xs)
Here we manage to create (x,y,z) by pattern matching on [x,y,z], but what if there were more than three tuples, our pattern matching would no longer be valid?
So you should ask yourself the question what it is you're really trying to accomplish with this code and what scenarios might occur (e.g.: empty tuples, tuples with varying lengths mutually, .. ?) and also, how should your program handle these different cases?
If there is no functional reason as to why you like the output to be in a tuple, I suggest you keep the function as is.
Good luck!
Why cannot one define operator := in GHC? Can this limitation be eliminated in future releases?
Here is output:
[1 of 1] Compiling Images ( Images.hs, interpreted )
Images.hs:19:1:
Invalid type signature: (:=) :: HasSetter s => s a -> a -> IO ()
Should be of form <variable> :: <type>
Constructors vs functions
Constructors make new data types out of old data. Let's roll our own list:
data List a = Empty | Cons a (List a)
myList = Const 1 (Cons 2 Empty) -- 1:2:[] =[1,2]
uncons x' (Cons x xs) = if x == x' then xs else Cons x xs
Here, Cons :: a -> List a is a special function that takes an element and a list and makes a longer list.
It's important that there's a difference between constructor functions and ordinary functions, so that the compiler knows which one is valid in a pattern match:
headM (Cons x xs) = Just x
headM Empty = Nothing
That makes sense, but this doesn't:
previousHead (uncons x xs) = Just x
previousHead xs = Nothing
because how can the computer know which element you removed or whether you did remove one?
Infix Constructors and functions
Sometimes, as with lists, it's helpful to have a constructor work infix, so we actually have the equivalent of
data [a] = [] | a:[a]
so we can write lists like 1:2:[].
Infix functions need to be separate from identifiers so we can write x:xs unambiguously without spaces, so infix functions (including infix constructors like : have to consist entirely of symbols, not letters.
The compiler still needs to be able to tell constructors apart from ordinary functions when they're infix, so we need the equivalent of the rule that constructors start with a capital. The language designers designated : as the only capital symbol, so infix constructors have to start with it, and ordinary functions can't.
What you can do with :=
You can use := as a constructor, so you could define
data Assignment a = Variable := Expression a
But if you want to call an ordinary function :=, you can't, because : isn't allowed at the front as it counts as the capital symbol, you'd have to start with something else, for (simple but pointless) example:
(.:=) :: Maybe a -> a -> Maybe a
Nothing .:= x = Just x
Just y .:= x = Just x
First time poster, but this site has helped me alot.
I am trying to learn Haskell.
This is the question i'm asked to answer.
Write a function that takes a list (length >=2) of pairs of length and returns the first component of the second element in the list. So, when provided with [(5,’b’), (1,’c’), (6,’a’)], it will return 1.
I have done this myself.
listtwo :: [([a],b)] -> [a]
listtwo [] = []
listtwo [(a,b)] = fst (head (tail [(a,b)]))
I am trying to take a list of lists tuples I believe and return the 1st element from the 2nd item in the list. I know if you take out the [(a,b)]'s and replace the second [(a,b)] with a list like the one in the question it works fine. But when I try to make this function work for ANY list of tuples. I get errors.
Error I recieve
<interactive>:1:27:
No instance for (Num [a0])
arising from the literal `6'
Possible fix: add an instance declaration for (Num [a0])
In the expression: 6
In the expression: (6, 'a')
In the first argument of `listtwo', namely
`[(5, 'b'), (1, 'c'), (6, 'a')]'
So i'm asking if anyone can help me deciver the errors and mabye explain what I am doing wrong (don't give me the answer, cant learn that way).
Appriciate the help, might have more questions if this gets answered. Thank you very much in advance!
You say that you want a function that returns the first component of the second element of the list. The best way to write this function will be by pattern matching. But first, let's think about its type.
Say you want a list of tuples of (Int,Char). This is written as [(Int,Char)]. If you want a list of 2-tuples of arbitrary type, you replace the types Int and Char with type variables, so you end up with the type [(a,b)].
Your function needs to take something of this type, and return the first component of the second element of the list. All of the first components of the tuples have type a, so your return type must be a as well. So your function's type signature is
f :: [(a,b)] -> a
Now, how do we write this function? The best way is to use pattern matching. This is a neat way to extract the components of a data structure without having to use accessors (aka getters, if you come from an object-oriented background). Let's say we have a function g :: [a] -> a which returns the third component of a list. You could write
g :: [a] -> a
g xs = head (tail (tail xs))
but that looks pretty nasty. Another way is to pattern match. A list with three elements [x,y,z] can be constructed by doing x : y : z : [] where x, y and z are all of type a (remember that the operator : adds items to the front of a list). So we can write:
g :: [a] -> a
g (x : y : z : []) = z
But there's a problem with this - it only works on lists of length three, because our pattern says "Match a list of three elements with the empty list tacked on the end." Instead, we could use the pattern x : y : z : rest, where now rest matches the rest of the list:
g :: [a] -> a
g (x : y : z : rest) = z
where our pattern now says "Match a list of three elements followed by anything else at all." In fact, we can make it simpler. We aren't going to use the values x, y or rest so we can replace them with the Haskell pattern _ (underscore). This matches anything, and makes us promise that we aren't going to use that value:
g :: [a] -> a
g (_ : _ : z : _) = z
How can we use this to solve your problem? Well, if you had a list matching the pattern (w,x) : (y,z) : rest you would want to return y. So you can write:
f :: [(a,b)] -> a
f ( (w,x) : (y,z) : rest ) = y
which will work fine. However, you don't care about the first pair at all, so you can replace (w,x) with _. You also don't care about the second element of the second tuple or the rest of the list, so you can replace them with _ as well, getting:
f :: [(a,b)] -> a
f ( _ : (y,_) : _) = y
Checking it in ghci:
ghci> f [(5,'b'),(1,'c'),(6,'a')]
1
So it behaves as you expected it to.
I am reading a tutorial that uses the following example (that I'll generalize somewhat):
f :: Foo -> (Int, Foo)
...
fList :: Foo -> [Int]
fList foo = x : fList bar
where
(x, bar) = f foo
My question lies in the fact that it seems you can refer to x and bar, by name, outside of the tuple where they are obtained. This would seem to act like destructuring parameter lists in other languages, if my guess is correct. (In other words, I didn't have to do the following:)
fList foo = (fst tuple) : fList (snd tuple)
where
tuple = f foo
Am I right about this behavior? I've never seen it mentioned yet in the tutorials/books I've been reading. Can someone point me to more info on the subject?
Edit: Can anything (lists, arrays, etc.) be destructured in a similar way, or can you only do this with tuples?
Seeing your edit, I think what your asking about is Pattern matching.
And to answer your question: Yes, anything you can construct, you can also 'deconstruct' using the constructors. For example, you're probably familiar with this form of pattern matching:
head :: [a] -> a
head (x:xs) = x
head [] = error "Can't take head of empty list"
However, there are more places where you can use pattern matching, other valid notations are:
head xs = case xs of
(y:ys) -> y
[] -> error "Can't take head of empty list"
head xs = let (y:ys) = xs
in y
head xs = y
where
(y:ys) = xs
Note that the last two examples are a bit different from the first to because they give different error messages when you call them with an empty list.
Although these examples are specific to lists, you can do the same with other data types, like so:
first :: (a, b) -> a
first tuple = x
where
(x, y) = tuple
second :: (a, b) -> b
second tuple = let (x, y) = tuple
in y
fromJust :: Maybe a -> a
fromJust ma = x
where
(Just x) = ma
Again, the last function will also crash if you call it with Nothing.
To sum up; if you can create something using constructors (like (:) and [] for lists, or (,) for tuples, or Nothing and Just for Maybe), you can use those same constructors to do pattern matching in a variety of ways.
Am I right about this behavior?
Yes. The names exist only in the block where you have defined them, though. In your case, this means the logical unit that your where clause is applied to, i.e. the expression inside fList.
Another way to look at it is that code like this
x where x = 3
is roughly equivalent to
let x = 3 in x
Yes, you're right. Names bound in a where clause are visible to the full declaration preceding the where clause. In your case those names are f and bar.
(One of the hard things about learning Haskell is that it is not just permitted but common to use variables in the source code in locations that precede the locations where those variables are defined.)
The place to read more about where clauses is in the Haskell 98 Report or in one of the many fine tutorials to be found at haskell.org.