Undiscovered Function Declaration Syntax?

I just accidentally discovered a function declaration syntax that I have never seen before

\> add :: Int -> Int -> Int = (+)
\> add 1 2
3
\> -- or with points
\> add' :: Int -> Int -> Int = \x y -> x + y
\> add' 3 4
7
\> -- multi line
\> :{
 > add''
 >   :: Int -> Int -> Int
 >   = \x      y
 >   -> x + y
 > :}
\> add'' 5 6
11

How come i have never seen this anywhere?

It is using the grammar for pattern type signatures.

1 Like
add1 (x :: Int) (y :: Int) = x + y
add2 (x :: Int) (y :: Int) :: Int = x + y
add3 = (+) :: Int -> Int -> Int
(add4 :: Int -> Int -> Int) = (+)

I’m a little surprised you don’t need the parens around your bare add (I do round my add4).

This is a variety of PatternSignatures I would say – except I’m struggling to find the reference for it. … Ah, here.

3 Likes

Pattern signatures are newer than most Haskell textbooks.

Moreover it is not like you can write (f :: Int -> Int -> Int) x y = x + y.

They go all the way back to 6.8.1 which was released in 2007. I think quite a few books were written after that.

1 Like

Furthermore, by the time you write polymorphic functions: This is rejected:

g :: a -> a = \x -> x    -- rejected

Generally, pattern bindings may not have type variables. (I don’t know why, but it’s documented.) Pattern bindings mean pattern = expr, and recall that a special case is var = expr such as g = \x -> x.

What you can do though is

g1 (x::a) = x::a
g2 = \(x::a) -> x::a
1 Like

OK, fine, correction:

Pattern signatures are not part of GHC default until GHC2021. GHC2021 is newer than most textbooks.

Correction to your correction: Pattern signatures used to be part of GHC, and Hugs vintage 2006 – as a somewhat loosely documented extension. Then they got taken out of GHC; then put back in GHC2021. I think there’s work in hand to put back result signatures per my add2 above(?) But in a more limited form than was always supported in Hugs.

(I freely admit to having not kept up.)

Thank you for pointing out this polymorphic deficiency!