Created
July 9, 2020 11:48
-
-
Save MilesMcBain/e7a5b718161ddd13a5248d6a561da738 to your computer and use it in GitHub Desktop.
anonymous function examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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