How to use the Apply for Function Application

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 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 to convert validate function to use apply2 ?

+5
source share
1 answer

The type constructor for Validate takes two parameters, but Apply can only be parameterized with a constructor of type arity one. You need a special lambda type trick that allows us to curry a type definition:

 def validate(a : String) = Apply[({type λ[Int] = Validation[String, Int]})#λ].apply2(one(a), two(a)){_ + _} 
+4
source

Source: https://habr.com/ru/post/1264383/


All Articles