I have got 2 exercise, but I do not understand how can I make them work. I tried to figure it out but I don't understand. Can I get some help?
- Specify the function that produces an ordered pair from a list. The first element of the pair is the first element of the list and the second element of the pair is part of the tail of the list be. We can assume that the list is not empty.
headTail :: [a] -> (a, [a])
headTail (l: ls) = (headTail l, [ls])
- Give the function that gets two lists and produces an ordered pair, the first element of which is the first element of the first list, the second element of which is the second list first element! We can assume that none of the lists are empty.
doubleHead :: [a] -> [b] -> (a, b)
doubleHead (l:ls) =
CodePudding user response:
I would use pattern matching in both cases.
(l:ls)
assigns the first element of the list to l
and the rest to ls
. You can return them as a tuple as instructed.
headTail :: [a] -> (a, [a])
headTail (l:ls) = (l, ls)
Here we only care about the first elements of both lists. So, we pattern match them into x
, and y
and don't capture the rest at all (indicated by _
). And return them as a tuple.
doubleHead :: [a] -> [b] -> (a, b)
doubleHead (x:_) (y:_) = (x, y)