Scala Functional Patterns
БесплатноБез исполняемых скриптовНе проверенUse when functional programming patterns in Scala including higher-order functions, immutability, pattern matching, algebraic data types, monads…
от TheBushidoCollective★ 202 звезды на GitHubОб этом скилле
Scala Functional Patterns
Introduction
Scala uniquely blends object-oriented and functional programming paradigms, enabling developers to leverage the best of both worlds. Functional programming in Scala emphasizes immutability, pure functions, and composability, leading to more predictable and maintainable code.
Core functional patterns in Scala include higher-order functions, immutable data structures, pattern matching, algebraic data types (ADTs), monadic composition, for-comprehensions, and type classes. These patterns enable elegant solutions to complex problems while maintaining type safety.
This skill covers immutability principles, higher-order functions, pattern matching, ADTs with sealed traits, Option and Either monads, for-comprehensions, function composition, and functional error handling.
Immutability and Pure Functions
Immutable data structures and pure functions form the foundation of functional programming, ensuring predictable behavior and thread safety.
// Immutable case classes
case class User(
id: Int,
name: String,
email: String,
age: Int
)
// Copying with modifications
val user = User(1, "Alice", "[email protected]", 30)
val updatedUser = user.copy(age = 31)
// Immutable collections
val numbers = List(1, 2, 3, 4, 5)
val doubled = numbers.map(_ * 2) // Original list unchanged
// Pure functions (deterministic, no side effects)
def add(a: Int, b: Int): Int = a + b
def multiply(a: Int, b: Int): Int = a * b
def calculateTotal(price: Double, quantity: Int, discount: Double): Double = {
val subtotal = price * quantity
val discountAmount = subtotal * discount
subtotal - discountAmount
}
// Impure function (side effect: logging)
def impureAdd(a: Int, b: Int): Int = {
println(s"Adding $a and $b") // Side effect
a + b
}
// Separating pure logic from side effects
def pureCalculation(items: List[Double]): Double =
items.sum
def displayResult(result: Double): Unit =
println(s"Total: $result")
val items = List(10.0, 20.0, 30.0)
val total = pureCalculation(items)
displayResult(total)
// Immutable data transformations
case class Order(items: List[String], total: Double)
def addItem(order: Order, item: String, price: Double): Order =
order.copy(
items = order.items :+ item,
total = order.total + price
)
def applyDiscount(order: Order, percentage: Double): Order =
order.copy(total = order.total * (1 - percentage))
// Composing immutable transformations
val order = Order(List("Book"), 25.0)
val finalOrder = applyDiscount(addItem(order, "Pen", 5.0), 0.1)
// Immutable builder pattern
case class PersonBuilder(
name: Option[String] = None,
age: Option[Int] = None,
email: Option[String] = None
) {
def withName(n: String): PersonBuilder = copy(name = Some(n))
def withAge(a: Int): PersonBuilder = copy(age = Some(a))
def withEmail(e: String): PersonBuilder = copy(email = Some(e))
def build: Option[Person] = for {
n <- name
a <- age
e <- email
} yield Person(n, a, e)
}
case class Person(name: String, age: Int, email: String)
val person = PersonBuilder()
.withName("Bob")
.withAge(25)
.withEmail("[email protected]")
.build
Immutability eliminates entire classes of bugs related to shared mutable state and enables safe concurrent programming.
Higher-Order Functions
Higher-order functions accept functions as parameters or return functions, enabling powerful abstraction and code reuse.
// Functions as parameters
def applyOperation(x: Int, y: Int, op: (Int, Int) => Int): Int =
op(x, y)
val sum = applyOperation(5, 3, (a, b) => a + b)
val product = applyOperation(5, 3, (a, b) => a * b)
// Functions as return values
def multiplyBy(factor: Int): Int => Int =
(x: Int) => x * factor
val double = multiplyBy(2)
val triple = multiplyBy(3)
println(double(5)) // 10
println(triple(5)) // 15
// Currying
def curriedAdd(a: Int)(b: Int): Int = a + b
val add5 = curriedAdd(5) _
println(add5(3)) // 8
// Partial application
def greet(greeting: String, name: String): String =
s"$greeting, $name!"
val sayHello: String => String = greet("Hello", _)
println(sayHello("Alice")) // Hello, Alice!
// Function composition
val addOne: Int => Int = _ + 1
val multiplyByTwo: Int => Int = _ * 2
val addThenMultiply = addOne andThen multiplyByTwo
val multiplyThenAdd = addOne compose multiplyByTwo
println(addThenMultiply(5)) // (5 + 1) * 2 = 12
println(multiplyThenAdd(5)) // (5 * 2) + 1 = 11
// Collection operations with higher-order functions
val numbers = List(1, 2, 3, 4, 5)
val squared = numbers.map(x => x * x)
val evens = numbers.filter(_ % 2 == 0)
val sum = numbers.reduce(_ + _)
val product = numbers.fold(1)(_ * _)
// FlatMap for nested transformations
val nested = List(List(1, 2), List(3, 4), List(5))
val flattened = nested.flatMap(identity)
val pairs = numbers.flatMap(x => numbers.map(y => (x, y)))
// Custom higher-order functions
def retry[T](times: Int)(operation: => T): Option[T] = {
@
Установить Scala Functional Patterns в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Scala Functional Patterns?
Use when functional programming patterns in Scala including higher-order functions, immutability, pattern matching, algebraic data types, monads, for-comprehensions, and functional composition for building robust, type-safe applications.
Как установить скилл Scala Functional Patterns?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Scala Functional Patterns запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic