score:5

Accepted answer

you can get some of the behavior you're after with the switch function. however, r does not have sum types like the ones you're used to in scala and f#.

r is a dynamic language, a lot like scheme and lisp but with different syntax. you're going to have to make a few adjustments if you're coming from a strongly typed language like f# or scala. you lose the benefits of strong types, but you gain the benefits of dynamic ones.

it turns out that for data analysis, dynamic typing is often a better fit.

score:1

r is... very different. to do something like that, you would use s4 generics and method dispatch, which use a signature to access methods. it would essentially reproduce the behavior inside your matcher object. here is the sample code:

#- typical r oo code uses the concept of generic function dispatch. to use "work" as a
#- method, i need to set the generic function, from which all other methods will be
#- dispatched from. normally, r does this by default, but it is always nicer to declare it
#- directly, as it shows that you *own* said generic. this is the example for s4 methods, 
#- so the dispatching might look weird at first (?).

require("methods")
setgeneric("work", function(one, two) print("default"))

#- now that we have a generic, we can create your classes and use method
#- dispatch to produce a similar effect to your pattern matcher.
setclass("a")
setclass("b", contains = "a")
setclass("c", contains = "a")


# now, the equivalent for your "cases" in r...
setmethod("work", c(one = "b", two = "b"), function(one, two) print("b"))
setmethod("work", c(one = "b", two = "c"), function(one, two) print("c"))

work(new("b"), new("b"))
# b

work(new("b"), new("c"))
# c

#- just an additional print call to make it obvious
work()
# default

note that i could have just as well defined it for independent classes "b" and "c", and it would have worked. secondly, encapsulating this code inside an object as you did would be very tedious (e.g. using r6/reference classes or something like that), and highlights the difference with r. functions just love to live outside objects in r, and so it is easier to dispatch them with the object you intend to use them in as an additional argument for the signature, rather than placing them inside a particular object structure.


Related Query

More Query from same tag