Methods in Racket
Racket supports methods defined on struct types, which are similar to object-oriented programming concepts in other languages.
To run the program, save it as methods.rkt
and use the racket
command:
In this Racket version:
We define a
rect
struct withwidth
andheight
fields.We define
area
andperim
functions that take arect
as an argument. These are analogous to methods in object-oriented programming.In the
main
function, we create arect
instance and call our defined functions on it.Unlike Go, Racket doesn’t distinguish between value and pointer receivers. The same functions work for both the struct and references to it.
Racket’s functional programming paradigm means we don’t need to worry about mutating the receiving struct. If we needed to modify the struct, we would typically create a new instance with the modified values.
Next, we’ll look at Racket’s mechanism for grouping and naming related sets of functions, which is typically done through modules rather than interfaces.