I have the following validation logic:
def one(a : String) : Validation[String, Int] =
if (a == "one") {
Success(1)
} else {
Failure("Not One")
}
def two(a : String) : Validation[String, Int] =
if (a == "two") {
Success(2)
} else {
Failure("Not Two")
}
def validate (a : String) = (one(a) |@| two(a)){_ + _}
According to the Scalaz documentation:
/**
* DSL for constructing Applicative expressions.
*
* `(f1 |@| f2 |@| ... |@| fn)((v1, v2, ... vn) => ...)` is an alternative to `Apply[F].applyN(f1, f2, ..., fn)((v1, v2, ... vn) => ...)`
*
* `(f1 |@| f2 |@| ... |@| fn).tupled` is an alternative to `Apply[F].applyN(f1, f2, ..., fn)(TupleN.apply _)`
*
* Warning: each call to `|@|` leads to an allocation of wrapper object. For performance sensitive code, consider using
* [[scalaz.Apply]]`#applyN` directly.
*/
How do I convert the validate function to use apply2
?
Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.
The apply() method allows you to apply a function along one of the axis of the DataFrame, default 0, which is the index (row) axis.
The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array. Return Value: It returns the method values of a given function.
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
Type constructor for Validate
takes two parameters, but Apply
can only be parameterized by a type constructor of arity one. You need a special trick called type lambda which allows us to curry the type definition:
def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_ + _}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With