Reputation:
I'm pretty new to Haskell so I'm still getting the ropes of everything. I want to write two functions where the first one takes a list of Integers and returns the first element. The second function does the same but returns the last element. So far I have
firstList :: [Integer] -> Integer
firstList [] = 0
firstList (_:xs) = head xs
lastList :: [Integer] -> Integer
lastList [] = 0
lastList (_:xs) = (last) xs
The lastList function seems to be working but not firstList. For example, for the list [3, 1, 2, 4]; it returns 1 and not 3. How can I improve my code?
Upvotes: 0
Views: 674
Reputation: 127
As I understand this question, you want the two function to return 0 when given an empty list and otherwiese the first or last element respectivly.
Haskell code:
firstList :: [Integer] -> Integer
firstList [] = 0
firstList (x:_) = x
In your code xs is the remaining portion of the list and thus head returns the second element of the original list
Upvotes: 0
Reputation: 120711
You seem to be mixing two possible approaches to this problem:
The no-effort approach
firstList :: [Integer] -> Integer
firstList = head
...or by β-expansion firstList xs = head xs
. This simply invokes the standard head
function without doing anything else. Which is certainly a way to solve the problem, but probably not what's expected in this task.
The all-manual approach
firstList [] = ...
firstList (x:xs) = ...
In this setting, you're not calling anything from the libraries, but manually figuring out what to do with the head and tail (if any) of the list. Well, for firstList
this is straightforward enough: you just use the head-element, i.e. x
. Nothing more needs to be done, no further function to be called.
OTOH, for lastList
you'll actually need to do some more. Specifically, as chi commented, you don't actually handle the 1-element case, because you always strip away the head-element, if there's any. If that's the only element, then last
doesn't get any to work with. What you should actually do there is not call a standard function at all, but instead handle all the relevant cases manually and the recurse with your own function.
lastList [] = ...
lastList [x] = ...
lastList (_:xs) = lastList xs
Upvotes: 4