Re:Show HN: Create Music with R
by tgv on Saturday July 13, 2024 @03:36AM
(#40952479)
Using the addition operator for manipulation is a bit unusual. Why did you choose it? I don't have R studio or anything on my computer, so I can't test it, but do things like
work?
[ Parent
| on HN ]
In base R, `+` is the usual arithmetic operator for numeric and complex vectors. I'm not a super R expert but I'm pretty sure the addition operator is overloaded here. It simply means:
add(Music(), Meter(4, 4), Line(...), Line(...), Articulation(">", 1))
Edit. Found the definition in the source [1]. I think the approach is similar to Go's approach to method definition [2]. Methods are defined on types, i.e., methods are functions with special receiver arguments. The infix notation instead of prefix notation is just syntactic sugar.[1] https://github.com/flujoo/gm/blob/69d639be86b0cef80d815a73a6...
This is quite idiomatic for R; packages like ggplot do the same thing to, for instance, build up graphics- see https://r4ds.hadley.nz/data-visualize for some nice examples
Re:Show HN: Create Music with R
by erikgahner on Saturday July 13, 2024 @05:04AM
(#40952757)
ggplot2 is pretty much an exception at this point, and if the package was created today it would use the pipe instead of add [1]. Most packages use pipes now (especially with the introduction of the pipe operator in R 4.1.0).
Re:Show HN: Create Music with R
by dr_kiszonka on Saturday July 13, 2024 @11:59AM
(#40954791)
I am no R expert, but pipes don't seem the most intuitive for ggplot. This is because they would imply that, e.g., ggtitle() %>% geom_point() means that ggtitle() outputs an input for geom_point().
That’s exactly how ggplot (not 2!) worked: https://github.com/hadley/ggplot1
In creating a music score, you literally "add" components to the score. So it's natural to implement this operation this way. From the OOP perspective, it's just method overloading. Not uncommon in R development.