mul <- function(a, b) {
a * c # try to figure out why it doesn't work!
}2 Multiply
8kyu Tantangan #2/366 - 16 Feb 2024
https://www.codewars.com/kata/50654ddff44f800200000004
2.1 Instruction
This code does not execute properly. Try to figure out why.
mul <- function(a, b) {
a * c # try to figure out why it doesn't work!
}
2.2 YouTube Video
2.3 Solution Code
Karena argumen dari function mul() adalah a dan b sedangkan operasi perkalian di dalamnya menggunakan c yang belum diketahui dan tidak ada objek tersebut.
Solusi: ganti objek c di dalam function mul() dengan b dari argumen function tersebut.
mul <- function(a, b) {
a * b
}2.4 Test
library(testthat)
test_that("test for associativity of multiplication", {
a <- runif(1, 0, 10000)
b <- runif(1, 0, 10000)
c <- runif(1, 0, 10000)
expect_equal(mul(a, b), a * b)
expect_equal(mul(mul(a, b), c), a * b * c)
expect_equal(mul(a, mul(b, c)), a * b * c)
})Test passed 😸
