concept function in category scala

appears as: functions, function, The function, A function, function, The functions, functions, The function, The function
Get Programming with Scala

This is an excerpt from Manning's book Get Programming with Scala.

Functional Programming languages base their entire structure on functions. Functions play a big part in Scala as its “first-class citizens”. In lesson 6, you’ll learn their basics and how to define them. In unit 4, you’ll discover functional purity and its several advantages and to how you can use functions as parameters or return values: you refer to them as higher order functions. They allow you to create powerful abstractions that simplify and remove duplication of your code in a way that is usually not so easily achievable in an object-oriented approach. Listing 1.5 shows an example of a function that takes another function as its parameter, and that returns a new function.

scala> def sayHello(n: String): String = s"hi $n!"
sayHello: (n: String)String
 
scala> def sayHello(n: String): Int = s"hi $n!"
<console>:10: error: type mismatch;
 found   : String
 required: Int
       def sayHello(n: String): Int = s"hi $n!"
                                   ^
Figure 6.1: The different components of a Scala function. The function signature describes what a function does, and it has the def keyword, a name, some parameters, and a return type. The implementation provides detailed instructions on how a function does it.

A function is total if it is well-defined for every input: for every possible parameter it must terminate, and it must return a value that matches its return type.

Functional Programming in Scala

This is an excerpt from Manning's book Functional Programming in Scala.

Referential transparency forces the invariant that everything a function does is represented by the value that it returns, according to the result type of the function. This constraint enables a simple and natural mode of reasoning about program evaluation called the substitution model. When expressions are referentially transparent, we can imagine that computation proceeds much like we’d solve an algebraic equation. We fully expand every part of an expression, replacing all variables with their referents, and then reduce it to its simplest form. At each step we replace a term with an equivalent one; computation proceeds by substituting equals for equals. In other words, RT enables equational reasoning about programs.

def factorial(n: Int): Int = { def go(n: Int, acc: Int): Int = #1 if (n <= 0) acc else go(n-1, n*acc) go(n, 1) } #1: An inner function, or local definition. It’s common in Scala to write functions that are local to the body of another function. In functional programming, we shouldn’t consider this a bigger deal than local integers or strings.

The way we write loops functionally, without mutating a loop variable, is with a recursive function. Here we’re defining a recursive helper function inside the body of the factorial function. Such a helper function is often called go or loop by convention. In Scala, we can define functions inside any block, including within another function definition. Since it’s local, the go function can only be referred to from within the body of the factorial function, just like a local variable would. The definition of factorial finally just consists of a call to go with the initial conditions for the loop.

2.4. Higher-order functions: passing functions to functions

Now that we’ve covered the basics of Scala’s syntax, we’ll move on to covering some of the basics of writing functional programs. The first new idea is this: functions are values. And just like values of other types—such as integers, strings, and lists—functions can be assigned to variables, stored in data structures, and passed as arguments to functions.

When writing purely functional programs, we’ll often find it useful to write a function that accepts other functions as arguments. This is called a higher-order function (HOF), and we’ll look next at some simple examples to illustrate. In later chapters, we’ll see how useful this capability really is, and how it permeates the functional programming style. But to start, suppose we wanted to adapt our program to print out both the absolute value of a number and the factorial of another number. Here’s a sample run of such a program:

Scala in Action

This is an excerpt from Manning's book Scala in Action.

Functional programming takes more of a mathematical view of the world, where programs are composed of functions that take certain input and produce values and possibly other functions. The building blocks of functional programming are neither objects nor procedures (C programming style) but functions. The simple definition of functional programming is programming with functions.

It’s important to understand what is meant by function here. A function relates every value of the domain (the input) to exactly one value of the codomain (the output). Figure 1.1 depicts a function that maps values of type X to exactly one value of Y.

Figure 1.1. A pure function that maps values of X to exactly one value of Y

Another aspect of functional programming is that it doesn’t have side effects or mutability. The benefits of not having mutability and side effects in functional programs are that the programs are much easier to understand (it has no side effects), reason about, and test because the activity of the function is completely local and it has no external effects. Another huge benefit of functional programming is ease of concurrent programming. Concurrency becomes a nonissue because there’s no change (immutability) to coordinate between processes or threads. You’ll learn about the functional programming side of Scala throughout the book, particularly in chapter 10.

How do mathematical functions relate to functions in programming?

In mathematics, a function is a relation between a given set of elements called the domain (in programming we call this input) and a set of elements called the codomain (in programming we call this output). The function associates each element in the domain with exactly one element in the codomain. For example, f(x) = y could be interpreted as

Functional programming is all about functions, and Scala lets you create functions in various forms. Functions in Scala are first-class values. That means you can treat functions like Int or String as type values in Scala. You can create them as a value, pass them to functions as parameters, and compose them to create new functions.

5.3.1. Methods vs. functions

The common form of a function in Scala is defined as a member of a class. It’s called a method:

class UseResource {
  def use(r: Resource): Boolean = {...}
}

Here use is a method defined in the class UseResource. One downside of using methods is that it’s easy to depend on the state defined by the enclosing class without explicitly passing the dependencies as parameters—be careful about that because that will take you away from having pure methods. Unlike functions, methods don’t have any type associated with them. Scala infuses functional programming with OOP by transforming functions into objects. For example, you can assign a function literal (anonymous function) to a value like the following:

val succ = (x: Int) => x + 1

Here succ is associated with a function Int => Int and it’s nothing but a shorthand definition of the following:

val succFunction = new Function1[Int, Int] {
  def apply(x:Int) : Int = x + 1
}

Both of those definitions are equivalent. Functions in Scala are represented by a type and object, but methods aren’t. Methods are only associated with the enclosing class. The good news is that Scala lets you convert methods to functions using a transform process called Eta expansion. You can take any existing method and append _ (underscore) to create the function. The following code creates a function version of the use method from the previous example:

val use_func: Resource => Boolean = (new UseResource).use _

It’s common in Scala to convert methods into functions and pass them around to other functions. In the next section you’ll look into examples of higher-order functions and how they help you in solving problems.

Lift in Action: The Simply Functional Web Framework for Scala

This is an excerpt from Manning's book Lift in Action: The Simply Functional Web Framework for Scala.

As the name implies, functional programming languages have a single basic idea at their root: functions. Small units of code are self-contained functions that take type A as an argument and return type B as a result; this is expressed more directly in Scala notation: A => B. How this result is achieved is an implementation detail for the most part; as long as the function yields a value of type B, all is well.

Listing 14.10. Implementing the BookService using functions
trait BookService { val lookupBook: BookRepository => String => Option[Book] = repository => isbn => repository.lookup(isbn) val addBook: BookRepository => Book => Unit = repository => book => repository.add(book) }

It is typically idiomatic within Scala to give methods that have zero arguments no trailing parenthesis if the function is referentially transparent. For example Thing.foo is fine given a referentially transparent method, but if the method has side effects it would be idiomatic to write Thing.foo().