How to curry a … argument by position in R?

后端 未结 2 1303
野性不改
野性不改 2021-01-12 05:25

This may fall under \"you can\'t, and there\'s no reason to anyway,\" but I\'m curious if it\'s possible. At very least, maybe it will be a fun R puzzle.

I was pond

2条回答
  •  被撕碎了的回忆
    2021-01-12 05:46

    #1. Ignore the second argument of Curry and hard code the newline

    Try this which curries the last argument of cat by hard coding it in an anonymous function. It does not actually make use of Curry arguments after the first:

    catnip <- Curry(function(...) cat(..., "\n") )
    

    #2. Manufacture function by currying an anonymous function

    Here is a second solution which curries the last argument of cat by using an anonymous function which reorders cat's arguments.

    catnip2 <- Curry(function(last.arg, ...) cat(..., last.arg), "\n")
    
    # test
    catnip2("hi", "there")
    

    #3. Manufacture desired function by currying an even more basic function

    Perhaps the real point of all this is to see how we can take basic components and Curry them to get what we want. Thus we could define a general last.arg.fun and then manufacture the desired function by a curry of it:

    last.arg.fun <- function(FUN, last.arg, ...) FUN(..., last.arg)
    catnip3 <- Curry(last.arg.fun, cat, "\n")
    
    # test
    last.arg.fun(cat, "\n", "hi", "there")
    
    # test
    catnip3("hi", "there")
    

    We could do it in two steps if we needed last.arg.cat at some point:

    last.arg.cat <- Curry(last.arg.fun, cat)
    catnip4 <- Curry(last.arg.cat, "\n")
    
    # test
    last.arg.cat("\n", "hi", "there")
    
    # test
    catnip4("hi", "there")
    

    Note that each of the tests should produce a line saying hi there ended in a newline.

    EDIT: more solutions.

提交回复
热议问题