softshipper
softshipper

Reputation: 34071

How to compose two functions?

I have two functions, that I am trying to compose it:

  private def convert(value: String)
  : Path = decode[Path](value) match {


  private def verify(parsed: Path)
  : Path = parsed.os match {

I've tried as following:

verify compose convert _

The compiler complains:

[error] Unapplied methods are only converted to functions when a function type is expected.
[error] You can make this conversion explicit by writing `verify _` or `verify(_)` instead of `verify`.
[error]     verify compose convert _
[error]     ^
[error] one error found

I am trying to accomplish the following:

  def process(value: String)
  : Path =
    verify(convert(value))

What am I doing wrong?

Upvotes: 3

Views: 2234

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31222

The problem is not everything in scala is a function. convert and verify in your example are methods not functions.

1) If you want to compose functions, define as functions as example below,

functions,

scala> def convert: String => String = (value: String) => "converted"
convert: String => String

scala> def verify = (value: String) => if(value == "converted") "valid" else "invalid"
verify: String => String

compose fns

scala> def vc = verify compose convert
vc: String => String

apply fn composition to functor

scala> Some("my-data").map{ vc.apply }
res29: Option[String] = Some(valid)

2) The another way is convert your existing methods to functions as below,

scala> def vc = (verify _ compose (convert _))
vc: String => String

scala> Some("data to convert").map { vc.apply }
res36: Option[String] = Some(valid)

References

https://twitter.github.io/scala_school/pattern-matching-and-functional-composition.html

Chapter 21 - Functions/Function literals

Function composition of methods, functions, and partially applied functions in Scala

Upvotes: 8

Related Questions