Skip to content

Instantly share code, notes, and snippets.

@MilesMcBain
Created July 9, 2020 11:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MilesMcBain/e7a5b718161ddd13a5248d6a561da738 to your computer and use it in GitHub Desktop.
Save MilesMcBain/e7a5b718161ddd13a5248d6a561da738 to your computer and use it in GitHub Desktop.
anonymous function examples
## apply a function to square a list of numbers
square <- function(x) {
x^2
}
lapply(list(1,2,3), square)
## save some code and declare 'square' anonymously - i.e. never assign it anywhere
## using the name 'square'
lapply(list(1,2,3), function(x) { x^2 })
## save more code - drop {}
lapply(list(1,2,3), function(x) x^2 )
## All of above are valid currently.
## Proposal is an even more compact anonymous function syntax:
lapply(list(1,2,3), (x) => x^2)
## or
lapply(list(1,2,3), \(x) x^2)
## or
lapply(list(1,2,3) @(x) x^2)
## It's nothing more than a case of swapping 'function' for one of those above,
## saving 6 - 7 characters. Yes 6 - 7 characters is what the excitement is
## about. But it can declutter code if you use these types of expressions a lot.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment