1

I was asked to make a function that works like foldr but with non empty lists, that works like this: foldr1 f [x1,x2...xn] = f x1 (f x2...(f xn-1 xn)...).

So I defined it like this:

foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
foldr1 f _ = undefined

And I'm still getting "Non-exhaustive patterns in function foldr1" error, despite covering all possibilities. What am I doing wrong?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
  • I agree that it looks like you've covered all the possible cases - but isn't this exactly what `foldr1` does anyway? (PS isn't the "non-exhaustive patterns" error a runtime error rather than a compile-time one? If so, what input are you giving it when you get the error?) – Robin Zigmond Jan 15 '19 at 16:56
  • Yeah, just checked and learned that foldr1 is actually an existing function. This was part of an old exam question I'm doing for practice. The input I was trying is foldr1 (+) [1,2,3,4] – Jaime Fernández Jan 15 '19 at 16:58
  • 5
    How are you running this? Are you using GHCi? Are you loading this in a file or typing it in directly? I cannot reproduce this problem. – AJF Jan 15 '19 at 17:01
  • @AJFarmar I bet that is it! good catch. you should make it an answer. (or maybe find a duplicate...?) closed it. :) – Will Ness Jan 15 '19 at 17:04
  • Running this on WinGHCi – Jaime Fernández Jan 15 '19 at 17:14

0 Answers0