Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Apply for Function Application

Tags:

scala

scalaz

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?

like image 299
M.K. Avatar asked Feb 18 '17 12:02

M.K.


People also ask

How does the apply function work?

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.

What is apply () in Python?

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.

What does apply () do in Javascript?

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.

What is the difference between call () and apply ()?

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.


1 Answers

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)){_  + _}
like image 92
slouc Avatar answered Sep 21 '22 22:09

slouc