Skip to content

Literal types #32

Closed
Closed

Description

@lawremi

A bit of a crazy idea, but is it worth considering defining a Class a literal value? Like a method with newClass(parent="foo") in its signature would only be dispatched to by the exact value "foo". This would be useful, for example, when conditioning on a file extension, or the value of "method" parameter. Essentially it would be using dispatch to implement switch/case statements. In the past, I've done something like new(paste0(fileExt, "File")) to implement this.

Activity

  1. hadley commented on Oct 7, 2020

    @hadley
    Member

    It occurred to me that we could also offer the flip side of this — a switch-style statement that uses dispatch:

    switchClass(x,
      Factor := "a factor",
      Character := "a character",
      "default"
    )
  2. hadley commented on Oct 22, 2021

    @hadley
    Member

    @lawremi do you still think this is important? My sense is that we should just close it, and wait to see if it arises in real life.

    I still think switchClass() is a cool idea, but implementing it at the package level is awkward because you'd have to use NSE to get the object on the LHS of :=/=.

  3. lawremi commented on Oct 23, 2021

    @lawremi
    CollaboratorAuthor

    Not very important, we can close.

  4. mikmart commented on Dec 3, 2022

    @mikmart

    @hadley @lawremi Could literal types (specifically unions of literal types) be used to specify that a property must be in a finite set of possible values, like in TypeScript? Essentially replacing the common match.arg() constructions? So you could do e.g.:

    api_query <- new_class(
      "api_query",
      properties = list(
        format = new_union("xml", "json")
      )
    )

    Instead of:

    library(R7)
    
    api_query <- new_class(
      "api_query",
      properties = list(
        format = new_property(
          class = class_character,
          setter = function(self, value) {
            prop(self, "format") <- match.arg(value, c("xml", "json"))
            self
          }
        )
      )
    )
    
    api_query(format = "xml")
    #> <api_query>
    #>  @ format: chr "xml"
    api_query(format = "csv")
    #> Error in match.arg(value, c("xml", "json")): 'arg' should be one of "xml", "json"
  5. hadley commented on Dec 3, 2022

    @hadley
    Member

    If we did want to support that, I think I'd prefer an explicit enum type.

  6. mikmart commented on Dec 3, 2022

    @mikmart

    Enums would be nice, especially if there was a switch or “match” statement to make using them a bit more ergonomic than just if-statements. But they might be quite cumbersome for the match.arg() replacement case.

    You’d need to define the enum elsewhere first, and then handle converting the enum variants into strings, rather than being able to just use the property directly. I’m imagining usage would look something like this:

    result_format <- enum(xml = 1, json = 2)
    
    api_query <- new_class(
      "api_query",
      properties = list(
        format = result_format
      )
    )
    
    q <- api_query(format = result_format$xml)
    
    fmt <- if (q@format == result_format$xml) {
      "xml"
    } else if (q@format == result_format$json) {
      "json"
    }
    
    httr::GET("https://some.api", query = list(fmt = fmt))

    Versus with literal unions:

    api_query <- new_class(
      "api_query",
      properties = list(
        format = new_union("xml", "json")
      )
    )
    
    q <- api_query(format = "xml")
    
    httr::GET("https://some.api", query = list(fmt = q@format))
  7. mikmart commented on Dec 4, 2022

    @mikmart

    I made a “proof of concept” branch to test this out:

    library(R7) # remotes::install_github("mikmart/OOP-WG@literal-classes")
    
    class_literal("GET")
    #> <R7_literal_class>: "GET"
    
    class_http_method <- new_union("GET", "POST", "PUT", "DELETE")
    class_http_method
    #> <R7_union>: "GET", "POST", "PUT", or "DELETE"
    
    request <- new_class(
      "request",
      package = "mypkg",
      properties = list(method = class_http_method)
    )
    request
    #> <R7_class>
    #> @ name  :  request
    #> @ parent: <R7_object>
    #> @ properties:
    #>  $ method: "GET", "POST", "PUT", or "DELETE"
    
    request()
    #> <mypkg::request>
    #>  @ method: chr "GET"
    request(method = "POST")
    #> <mypkg::request>
    #>  @ method: chr "POST"
    request(method = "foo")
    #> Error: <mypkg::request> object properties are invalid:
    #> - @method must be "GET", "POST", "PUT", or "DELETE", not <character>

    And generics:

    foo <- new_generic("foo", "x")
    foo(1L)
    #> Error: Can't find method for generic `foo()` with dispatch classes:
    #> - x: 1L, integer
    
    method(foo, class_integer) <- function(x) "It's an integer!"
    foo(1L)
    #> [1] "It's an integer!"
    
    method(foo, class_literal(1L)) <- function(x) "It's a one!"
    foo(1L)
    #> [1] "It's a one!"

    @hadley does this impact your thinking on this? Personally I think it's pretty expressive.

  8. mikmart commented on Dec 4, 2022

    @mikmart

    (And actually it should probably be like class_literal_union("GET", "POST") instead of new_union("GET", "POST") so that as_class("GET") doesn't have to work.)

  9. hadley commented on Dec 4, 2022

    @hadley
    Member

    I don't understand why your proposal couldn't be made to work with enum() instead of new_union(). But I think it'd be better to discuss this in a new issue. Do you mind opening one with a summary of your proposal?

  10. mikmart commented on Dec 4, 2022

    @mikmart

    I'm assuming enum members/variants should be considered opaque, as in it doesn't matter what the underlying value is. That would make them only useful for control flow, and since we don't have good constructs for control flow with arbitraty values (only really switch() which works with strings), that route could be cumbersome.

    I'll try to summarise in a new issue.

  11. hadley commented on Dec 4, 2022

    @hadley
    Member

    Oh I see what you mean now. I feel like there will be enough trade-offs (i.e. you can no longer see the possible options in the function signature, and two sets in one function will either need multiple dispatch or multiple generic helpers) that it'll only be worthwhile in limited situations, and so probably not something we'd want to add to R7 at this point.

  12. mikmart commented on Dec 4, 2022

    @mikmart

    @hadley I think in the (in my view) primary use case of validating class properties declaratively, literal classes would actually offer a big benefit in terms of being able to see the possible options. As for dispatch, I would see it as a fairly rare use-case to have a function that would dispatch on one, let alone multiple, literal union arguments.

    I spent some time summarising the benefits in this new issue in #267, I hope you find it useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions