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.
length
already needs to traverse the entire list. If you then recurse on that, you end up with a complexity of O (n ²) for a simple lookup! – leftaroundabout