Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

syntax extension for compact function definitions within a record

Tags:

haskell

The following syntax is the ordinary way of defining a function scoped to a module or within a where clause.

add :: Int -> Int -> Int
add x y = x + y

However, it does not work inside a record. At least by default, this is syntactically invalid

data RecordWithFunc = RecordWithFunc { func :: Int -> Int -> Int}

a :: RecordWithFunc
a = RecordWithFunc {
    func x y = x + y
}

Here's an example of the GHC frontend producing a parse error

$ runhaskell /tmp/hask.hs 

/tmp/hask.hs:5:10: error: parse error on input ‘x’
  |
5 |     func x y = x + y
  |          ^

Is there a syntax extension that enables arguments to appear after a field name?

like image 568
Gregory Nisbet Avatar asked Jan 19 '19 03:01

Gregory Nisbet


1 Answers

No, there is no such extension. (It would be nice though!) The usual method of doing this would be to say:

a :: RecordWithFunc
a = RecordWithFunc {
    func = \x y -> x + y
}

Or even, in this case:

a :: RecordWithFunc
a = RecordWithFunc {
    func = (+)
}
like image 170
bradrn Avatar answered Oct 08 '22 19:10

bradrn