Lay González
Lay González

Reputation: 2985

Is it possible to use F# record's labels as functions like in Haskell, or something similar?

In Haskell, given this record:

data ARecord { labelA :: String, labelB :: Int }

we get this functions:

labelA :: ARecord -> String
labelB :: ARecord -> Int

F# doesn't seem to work this way. But, is there something similar?

Edit

By something similar I mean something that saves me from having to define the functions manually, as @kaefer suggested.

Upvotes: 4

Views: 366

Answers (1)

kaefer
kaefer

Reputation: 5741

It's easily defined.

type ARecord = { labelA : string; labelB : int }
let labelA { labelA = s } = s
// val labelA : ARecord -> string

Edit

The following function would compile to identical IL, with direct read access to the backing field, instead of the automatically generated instance property. In contrast to normal experience with object-orientated dot-notation, it doesn't require type annotation to determine the record type.

let labelA' aRecord = aRecord.labelA
// val labelA' : aRecord:ARecord -> string

Upvotes: 2

Related Questions