Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell invalid type signature

Tags:

haskell

ghc

ghci

Quick question, what is wrong with this?

(get) :: [a] -> Int -> a   -- <- line 21
(x:xs) get 0 = x
(x:xs) get (n+1) = xs get n

ghci gives this error when I try to load the file that contains that code.

Prelude> :load ch6.hs 
[1 of 1] Compiling Main             ( ch6.hs, interpreted )

ch6.hs:21:0: Invalid type signature
Failed, modules loaded: none.

I'm trying to make get an infix operator.

like image 673
Kevin Avatar asked Dec 10 '22 03:12

Kevin


2 Answers

You shouldn't have parentheses around get, to start with. The syntax for the whole definition looks a bit off, though. I'm guessing you wanted something like this:

get :: [a] -> Int -> a
get (x:xs) 0 = x
get (x:xs) (n+1) = xs `get` n

Note the backticks around get in order to use it infix, which is necessary here because the rules for an alphanumeric identifier are different from operators: Operators are made of symbols, are are infix by default, and to write them without arguments or use them prefix, you put them in parentheses. Alphanumeric identifiers are prefix by default, and surrounding them with backticks lets you use them infix.

You can use the backticks on the left-hand side as well, if you want, but that looks a bit odd to my eye:

(x:xs) `get` 0 = x
(x:xs) `get` (n+1) = xs `get` n

Incidentally, the pattern syntax n+1 is deprecated, so you probably shouldn't use that. Instead, do this:

(x:xs) `get` n = xs `get` (n - 1)
like image 178
C. A. McCann Avatar answered Dec 21 '22 09:12

C. A. McCann


Just because you put it in parenthesis doesn't make it an infix function. Infix functions can only be made via symbols or backticks. See the Haskell report for specifics.

like image 43
Thomas M. DuBuisson Avatar answered Dec 21 '22 09:12

Thomas M. DuBuisson