Parse error in pattern: n + 1
Asked Answered
G

1

9

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?

Globin answered 6/12, 2013 at 18:32 Comment(4)
So-called n+k patterns are no longer supported in Haskell. See this question: #3749092Seals
You are right, I was following Erik Meijer's lessons which says this is possibleGlobin
@ChrisTaylor You should but this an answer so this question can be marked as closed and we can give you internet points.Bairn
You can use :set -XHaskell98 to make this work.Isa
S
10

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
Seals answered 7/12, 2013 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.