Невістка грубо поводиться й ображає, а син мовчить, прикриваючись її вагітністю

Моє життя в невеличкому містечку під Києвом перетворилося на пекло з того часу, як невістка, Соломія, завагітніла. Наші стосунки ніколи не були теплими, але до цього я стерпала її грубість, сподіваючись на мир у родині. Тепер вона перейшла всі межі: лає нас з чоловіком, кричить, принижує, а наш син, Тарас, мовчить, виправдовуючи її «становищем». Її хамство гризе мою душу, а бездіяльність сина болить найбільше.

Ми з чоловіком, Богданом, відразу зрозуміли, що Соломія — не подарунок. Груба, невихована, вона з перших днів дивилася на нас зі зневагою. А—
title: “Introduction to the Functional Programming Style in Scala”
date: 2020-05-27
header:
image: “https://res.cloudinary.com/dkoypjlgr/image/upload/c_auto,g_auto,h_300,w_1200/f_auto/q_auto:eco/v1715952116/blog_cover_large_phe6ch.jpg”
tags: [scala, functional programming]
excerpt: “Scala blends functional and object-oriented programming, and in this article I describe the best possible introduction to FP in Scala.”

This article is for the willing-to-learn-Scala programmer. Whether you’ve worked with Java (or another OOP language) before, or if you’re completely new to the Scala ecosystem, this gentle introduction will take steps to explore the functional programming style in Scala.

The code here is written in Scala 3, but most of the concepts apply to Scala 2 as well. If you’re new to Scala 3, make sure to check the [differences between Scala 2 and Scala 3](https://rockthejvm.com/blog/scala-3-is-coming).

## 1. Introduction – A Functional Programming Language?

When I first learned that Scala was a functional programming language, I was skeptical. I already knew that Scala had classes, objects, inheritance and polymorphism, encapsulation – all the good stuff from OOP I’ve learned in Java. So what gives?

### 1.1. What is Functional Programming Anyway?

The purest definition of FP stipulates that functional programming is programming with **mathematical functions** which have two critical properties:

1. they depend only on their input arguments, and nothing else; no reading from files, no DB queries, no user input, nothing
2. they only produce their results, and nothing else; no printing to the screen, no writing to a file, no writing to a DB, etc.

This is otherwise known as _pure functions_, and the FP style is only possible when we structure our code in terms of pure functions. In the purest of FP styles (e.g. Haskell), we can only use pure functions, and the responsibility of the language is to figure out how to run those functions in sequence to obtain the desired external effect (get user input, print to the screen, etc).

As you might figure, Scala is not pure in this sense. We can write pure functions, but Scala allows us to freely mix FP with side effects (reading/writing from/to external resources). That’s why Scala is said to be a _hybrid_ FP language: it gives us all the necessary tools for FP, but in a non-restrictive fashion.

### 1.2. Scala’s Core FP Features

Scala has all the features of a functional programming language:

– functions are first-class citizens, meaning we can manipulate functions just like any other value (pass as argument, return as result, store in a data structure, etc)
– Scala supports _anonymous functions_ out of the box (aka lambda functions)
– (almost) everything is an expression in Scala, meaning everything can be reduced to a value
– Scala allows no-side-effect functions (i.e. pure functions)
– Scala supports higher-order functions (HOFs): functions which take other functions as arguments and/or return other functions as results
– supports function composition and _currying_ (chaining functions with one argument)
– supports pattern matching (as a generalization of `switch` statements)
– algebraic data types, case classes, etc (more on those later in the course)

Because of this blend of FP and OOP, Scala has been called the “best of both worlds”. You can write both FP and OOP code in Scala.

### 1.3. Why Is Functional Programming Important?

Aside from the obvious theoretical appeal, FP has been growing in importance in recent years because of its advantages:

– modularity: FP is naturally modular because pure functions are naturally modular and composable (more composable than OOP methods)
– easier to understand: because pure functions only depend on their input (and not on the outside world), they’re much easier to read and understand
– easier to test: no mocks/stubs needed, because functions only depend on their arguments; testing pure functions is dead easy
– straightforward parallelism and concurrency: because pure functions don’t access or change shared data (by definition), they are naturally thread-safe, which means that parallelism is a breeze in FP
– works better with big data: because parallelism is trivial in FP, big data applications and distributed computing is much easier in FP than in OOP (if properly implemented)

Big data frameworks like Spark, Kafka, Flink and others are built with Scala, and they make heavy use of FP to abstract over distributed computations as if they were local.

## 2. Functions as First-Class Citizens

The first (and perhaps biggest) principle in FP is that **functions are values**. Just like numbers, strings, objects or any other data structure, functions can be stored in variables, data structures, can be passed as arguments or returned as results.

The functionality of treating functions as values is called _first-class functions_. In Scala, functions are values, and their types are instances of the `FunctionN` trait, where `N` is the number of arguments of that function.

### 2.1. Creating Functions

Let’s define a function which takes an integer and returns that integer + 1:

“`scala3
val incrementer = new Function1[Int, Int] {
override def apply(v1: Int): Int = v1 + 1
}
“`

This is a mouthful. Let’s unpack it:

– the type `Function1[Int, Int]` means a function with 1 argument of type Int and returns an Int
– the `apply` method is critical because Scala knows that anything with an `apply` method can be called like a function

Therefore, we can call `incrementer` like a function:

“`scala3
val two = incrementer(1)
“`

Now, that’s the expanded way of defining a function in Scala. The compiler can make our lives easier by using _syntactic sugar_:

“`scala3
val incrementer = (x: Int) => x + 1
“`

This means the same thing as above: we’re defining a function which takes an integer `x` and returns `x + 1`. The compiler expands this to the same `Function1[Int, Int]` trait as earlier.

### 2.2. Functions as Arguments (HOFs)

Because functions are values, we can pass them as arguments to other functions. Functions which take other functions as arguments/return other functions as results are called _higher-order functions_ (HOFs).

Let’s consider a function which takes another function and an integer, and returns the application of that function to that integer twice:

“`scala3
val applyTwice = (f: Int => Int, x: Int) => f(f(x))
“`

The type `Int => Int` is another piece of syntactic sugar which is identical to `Function1[Int, Int]`. We can then call `applyTwice` with our incrementer from earlier, and a number:

“`scala3
val four = applyTwice(incrementer, 2) // 4
“`

### 2.3. Anonymous Functions (Lambdas)

Just like we can use numbers without assigning them to a value first (e.g. `2 + 3` uses the numbers `2` and `3` directly), we can use functions without assigning them to a value first. These functions are called _anonymous functions_ (lambdas).

For example, we can call `applyTwice` with a lambda:

“`scala3
val eight = applyTwice((x: Int) => x * 2, 2)
“`

The lambda `(x: Int) => x * 2` is used as an argument for `applyTwice` without being assigned to a value first. This lambda is an instance of `Function1[Int, Int]` just like `incrementer` was, except this one is _anonymous_.

## 3. Everything is an Expression

Another tenet of Scala (and FP in general) is that _everything is an expression_. That is, every piece of code can be reduced to a value. This is in slight contrast with Java, where we can write _expressions_ (e.g. `1 + 3`) but also _statements_ like `for`, `while`, `if`, variable assignments, etc.

### 3.Тарас зателефонував через тиждень, але я навіть не захотіла слухати його виправдань.

Оцініть статтю
Та невже
Додати коментар

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!:

Невістка грубо поводиться й ображає, а син мовчить, прикриваючись її вагітністю
Та невже
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.