Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse error in pattern: n + 1

Trying to load a function within a file:

Prelude> :load "prova.hs"

prova.hs:37:9: Parse error in pattern: n + 1
[1 of 1] Compiling Main             ( prova.hs, interpreted )
Failed, modules loaded: none.
Prelude> 

This should create a list which contains n times the repeated value x:

ripeti :: Int -> a -> [a]
ripeti 0 x = []
ripeti (n+1) x = x:(ripeti n x)

What's wrong with it?

like image 531
Angelo Tricarico Avatar asked Dec 06 '13 18:12

Angelo Tricarico


1 Answers

Your code uses something called "n + k patterns" which are not supported in Haskell 2010 (they were supported in Haskell 98).

You can read a bit more about it at this SO question.

To get your code to work, you can write

ripeti :: Int -> a -> [a]
ripeti 0 x = []
ripeti n x = x : ripeti (n-1) x

Note that this will not terminate if you supply a negative value for n, so I would rather define

ripeti :: Int -> a -> [a]
ripeti n x | n <= 0    = []
           | otherwise = x : ripeti (n-1) x
like image 169
Chris Taylor Avatar answered Oct 17 '22 14:10

Chris Taylor