Skip to content

Allow for curried functions. #1190

Closed
Closed

Description

@jdoliner

I think we could make a number of awesome additions to our syntax by adding curried functions to our language. Passing functions is an integral part of our language at this point but it can get verbose quickly. It's important to keep in mind throughout this issue that there are drivers written in languages besides Ruby. @mlucy you use the argument "this is only marginally better than the alternative in Ruby" far too often and it leads to a protocol designed around Ruby.

The basic idea of a curried function is that you can construct a new function by passing an existing function fewer arguments than it normally takes. For example r.add is a function which normally takes 2 arguments (actually it's variadic right now but we'll talk about that later). If we allow for curried functions then r.add could be passed wherever we accept a 2 argument function, in particular it can be passed to reduce like so:

// old version
r.table("foo").reduce(function (left, right) { return left.add(right); })
// with currying
r.table("foo").reduce(r.add)

Currying also allows you to pass a single argument to a binary function to create a unary function. Suppose you have a stream of numbers and want to add one to them:

stream.map(r.add(1))

this also gets really nice if you add a pattern matching version of update. Consider the use case of incrementing a field:

// old version
r.table("foo").update(function (doc) { return {"counter" : doc("counter").add(1)}; })

// can be made shorter with r.row but that doesn't work in nested cases
r.table("foo").update({"counter" : r.row("counter").add(1))

// curried version, works everywhere
r.table("foo").update({"counter" : r.add(1)})

Curried functions are also absolutely awesome if you combine them with pattern matching filter syntax. For example consider the case of wanting to check if a user wrote a particular article:

// old version
r.table("foo").filter(function (doc) {return  doc("articles").contains(id);})

// curried version
r.table("foo").filter({"articles" : r.contains(id)})

I'm sure there are a bunch of other places we can find where curried functions are awesome.


It was pointed out by @mlucy that currying doesn't play nicely with variadic functions. I'm not 100% sure that it's impossible to have both although it seems like it might be. However I think that the syntax here is nice enough that it would be worth sacrificing variadic functions. I really don't think they're that useful to be honest. Basically all code I've seen written in Ruby and Python use infix + rather than variadic r.add and in Javascript people mostly do foo.add(1) rather than `r.add(foo, 1).

Activity

  1. jdoliner commented on Jul 19, 2013

    @jdoliner
    ContributorAuthor

    @coffeemug you and I spoke about this in person a while ago and one of the stumbling blocks we had was how to do things like swapping arguments and stuff. I think I have a pretty elegant solution to that actually. We can introduce a blank primitive (r._) it works like this:

    r.contains(r._, 5)
    // is equivalent to
    function (val) { return r.contains(val, 5); }
    
    r.contains([1,2,3], r._)
    // is equivalent to
    function (val) { return r.contains([1,2,3]), val); }

    I think this may be an advanced feature (mostly because it's hard to see the use case until you're in it) but I think it's pretty intuitive once you grok it.

    Additionally we can add a way to positionally curry arguments with r._0 r._1 etc.passing r._n as an argument to a function means: "return a new function and put the nth argument here" for example suppose I want to square an array of numbers:

    r.expr([1,2,3,4]).map(r.mul(r._0, r._0))

    again I think this is definitely going to be a pretty advanced feature but I do think it's pretty useful.

  2. coffeemug commented on Jul 19, 2013

    @coffeemug
    Contributor

    This is of a dup of #902. This has more information, is it ok if I close #902?

    A few thoughts:

    1. If we just limit currying to the sugary filter syntax then it would be awesome for users and would sidestep the variadic issue because we can special case it. Definitely not as nice as the full thing, though, but might be good enough.
    2. I don't think we need r._N. People can just use r._ multiple times. I think complete control over reordering is unnecessary.
    3. If we do the whole thing, it sounds like r._ sidesteps the variadic issues. You just say r.table("foo").reduce(r.add(r._, r._)). It's not strictly as nice as r.table("foo").reduce(r.add), but might be ok.

    This definitely sounds like a post #1174 feature, but it's really cool. If we can make it work, I would love to get this in.

  3. jdoliner commented on Jul 19, 2013

    @jdoliner
    ContributorAuthor

    But look at how cute r._0 is. I was planning to call it the salamander operator.

  4. mlucy commented on Jul 19, 2013

    @mlucy
    Member

    So, I'm a tiny bit confused at this point. How is r._ different from r.row?

    r.expr([1,2,3,4]).map(r.mul(r._, r._))
    r.expr([1,2,3,4]).map(r.mul(r.row, r.row))

    The set of features you're referring to as "currying" seems like three different things, at least to me:

    • seq.reduce(r.add) -- letting people pass the name of a function to reduce. I think that this is awesome. I also think that we should let people use the data aggregators from groupby here once the .group.map.reduce proposal comes around. (It's also something I think people will be familiar with -- Ruby lets you right seq.reduce(:+), and Python lets you pass the name of a function to reduce, which is what this looks like.)
    • seq.map(r.mul(r._, r._)) -- letting people use anaphora to specify functions in languages with verbose lambda syntax. We already have r.row for this purpose, and I would be hesitant to introduce multiple types of anaphora for this task. It might be cool to introduce something like r.row for positional arguments, though, so that you could use the shorter anaphoric syntax for functions of more than one variable.
    • seq.filter(r.contains(x)) -- automatic currying. I'm not very fond of this, for a few reasons:
      • It's of limited usefulness, because for many functions (like contains), you want to curry the second argument, not the first.
      • I don't think people will be familiar with this behavior -- none of our three client languages do automatic currying. (Actually, as far as I know, no languages with variadic functions do automatic currying.)
      • It doesn't play nice with variadic arguments. This doesn't just apply to our arithmetic operators -- basically all of our terms (e.g. contains, has_fields) are variadic when it makes sense, and I think that's really convenient.
      • It saves very little typing over the much more explicit seq.filter(r([1, 2, 3]).contains(r.row)). (Subpoint: because it's less explicit, attaching backtraces to it would be a pain in the ass -- if you write seq.filter(r.sub(1)) and you have an object in your sequence, no part of the user's query can be underlined for the backtrace, because the object in the sequence doesn't reside anywhere in the syntax tree of the sub expression.)
  5. mlucy commented on Jul 19, 2013

    @mlucy
    Member

    tl;dr -- I like the shorter syntax for reduce, I'm cautiously in favor of expanding our available anaphora where it makes sense, and I'm skeptical of automatic currying.

  6. AtnNn commented on Jul 19, 2013

    @AtnNn
    Member

    @mlucy 👍

  7. jdoliner commented on Jul 19, 2013

    @jdoliner
    ContributorAuthor

    r._ and associates aren't anaphora. They don't refer to any value which came before, They're ways of specifying where arguments go. Free your mind from the mentality of "whenever Joe writes code he's secretly just writing Common Lisp he just doesn't know it." I actually never wrote r.mul(r._, r_) I wrote r.mul(r._0, r._0) which is equivalent to lambda x: r.mul(x, x). r.mul(r._, r._) would be equivalent to lambda x,y: r.mul(x,y) which isn't a valid argument to map.

    It's of limited usefulness, because for many functions (like contains), you want to curry the second argument, not the first.

    That's what r._ is for and why it's not anaphora. You can curry to either side by writing:

    table.filter({"articles" : r.contains(1)})
    table.filter({"articles" : r.contains(r._, 1)})
    

    Also this want be a problem because in most cases where you want both orders we normally ending adding the other ordering as a different function. For example we're planning to add in which is really just equivalent to r.contains(r._1, r_0)

    I don't think people will be familiar with this behavior

    Mongo has a syntax that people love that looks like this:

    db.things.find(id: {$gt: oid});
    

    ours would be:

    table.filter({"id" : r.gt("id")})
    

    so I think this will be very familiar to mongo users. However this this syntax wasn't familiar to mongo users before mongo implemented it. They did it because it's just so readable that they knew people would like it even if it was new. I really think the niceness of this syntax justifies itself even if it's not present in the existing driver languages.

    It saves very little typing over the much more explicit seq.filter(r([1, 2, 3]).contains(r.row))

    The bad thing about this is that r.row only works one layer deep. Using currying you get a shorter syntax that works everywhere and is consistent. This is because it isn't anaphora.

  8. coffeemug commented on Jul 19, 2013

    @coffeemug
    Contributor

    Mongo has a syntax that people love

    One option here would be to just special case this syntax by essentially sugarizing filter (which we're already doing). I think it would give us 80% of the benefit with 20% of the work and 5% of pure PL awesomeness of currying, which may be acceptable.

  9. jdoliner commented on Jul 19, 2013

    @jdoliner
    ContributorAuthor

    I actually think filter and update are the 2 really important ones. Mongo also has a syntax like:

    table.update { db.collection.update( { $inc: { counter : 5 } }
    

    Ours would be just as good I think:

    table.update({"counter" : r.add(5)})
    

    I think if we implemented currying in those 2 places we could see how nice of a backend implementation of it we could get and also gauge people's reaction to this type of interface.

  10. coffeemug commented on Jul 19, 2013

    @coffeemug
    Contributor

    I think a lot of people already said this interface would be awesome. It seems awesome.

  11. mlucy commented on Jul 19, 2013

    @mlucy
    Member

    @jdoliner -- whoops, I guess I didn't quite parse your original comment on r._ correctly. Sorry if it felt like I was trying to pigeonhole it as something you weren't suggesting.

    Just to make sure I understand, r._ would be like r.row, except that it always binds to the tightest enclosing term rather than the tightest enclosing term that expects a 1-argument function, and it can bind to any argument of that term depending on its placement? E.g. if I wrote:

    r([2]).map(r([true]).contains(r.gt(r._, 1)))
    # `r.gt(r._, 1)` returns a function, so `r([true]).contains(r.gt(r._, 1))` returns `false` because `contains` can accept a function and BOOL < NUM, so we have `r([2]).map(false)` which gives `[false]`.
    r([2]).map(r([true]).contains(r.gt(r.row, 1)))
    # `r.gt(r.row, 1)` returns `true`, so `r([true]).contains(r.gt(r._, 1))` returns `true`, so we get `[true]`.

    Is that the semantics you were imagining?

    I'm a little bit confused by r._0. Specifically, let's say you write seq.map(r.mul(r._0, r._0)). That works. What if you wanted to do seq.map(r.add(r.mul(r._0, r._0), r._0)) instead? My current understanding is that that would fail, because r.mul(r._0, r._0) returns a function, and add doesn't accept a function. seq.map(r.add(r.mul(r.row, r.row), r.row)) would work, though, because the r.row binds to the map. Is this correct?

    Could you give me an example use case or two (aside from the filter/update syntax, which I talk about below) where you use r._ or r._0 (not r._1) somewhere where r.row doesn't work?


    I feel like the shortcut syntax for filter/update is sort of a different issue -- the biggest problem there is that we don't let people store functions in objects. E.g., even now it might be nice to be able to write table.update({'counter': lambda x: x+5}). If we do let people store functions in objects, then we have to worry about nontermination, because you can pass functions to other functions now.

    If we do let people store functions in objects, I still like the explicit functions with r._ in them better than the implicit currying: table.update({'counter': r._ + 5}).

    (Also, what's oid in the mongo syntax? A variable?)


    (Also, as an aside, I think I would refer to r._ as anaphora, since anaphora is just any expression whose reference depends upon another referential element, but the analogy is sort of stretched to begin with. Arguably both r.row and r._ are actually exaphora, since they refer to something that exists outside the query's text. But I'm cool if you want to call it something else; what's your preferred language to describe r._?)

  12. AtnNn commented on Jul 19, 2013

    @AtnNn
    Member

    Treating functions as partially applied only when in a filter or an update is a bad idea. It is too context-dependent and adds unnecessary magic.

    r._ has many corner cases. For example, what does foo.update({foo:r.pluck('a')}) mean? foo.update({foo: \x -> x.pluck('a') }) or foo.update(\x -> {foo: x.pluck('a')}) ?

  13. self-assigned this
    on Feb 22, 2014
  14. removed their assignment
    on Feb 25, 2015
  15. avimar commented on Aug 10, 2015

    @avimar

    Just to throw in an example: I'm using lodash-fp in my node.js projects for the auto-currying to make the code cleaner than using lodash.

  16. srh commented on May 20, 2017

    @srh
    Contributor

    I think Clojure's syntax #(+ %1 %2) is the thing to emulate here, it avoids ambiguity.

    r.fn(r._.add(r._2))
    r.fn.add(r._, r._2)
    function(x, y) { return x.add(y); }

    For what it's worth this could already be implemented in any driver.

  17. thelinuxlich commented on Mar 12, 2018

    @thelinuxlich

    @srh if it belongs to userland and there are many terms which lose context if trying to use partially, shouldn't this be closed?

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions