4 ms·
I was thinking of something like in F# (disclaimer: I've never used it and copied this from MSDN): type Shape = | Rectangle of height : float * width :
by captainmuon 12y ago
I was thinking of something like in F# (disclaimer: I've never used it and copied this from MSDN):
type Shape =
| Rectangle of height : float * width : float
| Circle of radius : float
let matchShape shape =
match shape with
| Rectangle(height = h) -> printfn "Rectangle with length %f" h
| Circle(r) -> printfn "Circle with radius %f" r
Admittedly, this is not too far from a simple `if`, but I believe the language ensures that you handle all cases.
The difference to OOP is that the code is in one place, with the function, instead of distributed, with all objects. It makes it easier to add functions, but harder to add new types. Often, this is the better option, but if you are writing truely extensible code (a library that gets passed custom objects, or an application with add-ins) then you want to go the OOP way.