Electric Coffee
Electric Coffee

Reputation: 12124

How would one implement OCaml / F#'s "function" construct in Scala?

A common tendency I've discovered in Scala is something like this:

def someFunction(a: SomeClass) = a match { ... }

And from there on a is never used ever again. This pattern is SO common in FP that OCaml and F# have a built-in construct to let you ditch that parameter entirely.

Instead of writing this:

let someFunction a = 
  match a with
  | 0 -> true
  | _ -> false

you can simply write this:

let someFunction =
  function
  | 0 -> true
  | _ -> false

So my question is, is it possible to write something like this in Scala?

def someFunction = function {
  case 0 => true
  case _ => false
}

Saving an otherwise unnecessary parameter.

I've attempted to write it as a function that takes a call-by-name parameter, but Scala won't let me make an empty match block.

Is it possible? Or does scala perhaps already have something like this built in?

Upvotes: 2

Views: 141

Answers (3)

Electric Coffee
Electric Coffee

Reputation: 12124

I've found a (very ugly) way of doing it

It's more of a hack/workaround than it is an actual solution, but I figured I'd post it here anyway

You can do this:

def something = (_: Int) match {
  case 0 => true
  case _ => false
}

This works and solves the problem, but it's ugly and clunkier to write than what I tried to get away from in the first place.

I'm curious to see what you guys can come up with.

Upvotes: 0

Lee
Lee

Reputation: 144176

You could use partial functions:

def function[A, B](mf: PartialFunction[A, B]): A => B = x => mf(x)

although this requires you to specify the type of the function on the left e.g.

def someFunction: Int => Boolean = function {
    case 0 => true
    case _ => false
}

Upvotes: 3

kiritsuku
kiritsuku

Reputation: 53358

Use a function instead of a method:

val someFunction: Int => Boolean = {
  case 0 => true
  case _ => false
}

You have to explicitly write the type annotations, but that must not be a drawback - for API usage it is useful documentation.

Upvotes: 8

Related Questions