Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Scala code examples - Jargon from the functional programming world in simple terms!

License

NotificationsYou must be signed in to change notification settings

ikhoon/functional-programming-jargon.scala

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Functional Programming Jargon

Functional programming (FP) provides many advantages, and its popularity has been increasing as a result. However, each programming paradigm comes with its own unique jargon and FP is no exception. By providing a glossary, we hope to make learning FP easier.

Examples are presented in Scala.Why Scala 3?

This is aWIP; please feel free to send a PR ;)

Where applicable, this document uses terms defined in theFantasy Land spec

Translations

Table of Contents

Arity

The number of arguments a function takes. From words like unary, binary, ternary, etc. This word has the distinction of being composed of two suffixes, "-ary" and "-ity." Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two. Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin. Likewise, a function that takes a variable number of arguments is called "variadic," whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below).

valsum= (a :Int,b:Int)=> a+ b// The arity of sum is 2// sum: (Int, Int) => Int = $$Lambda$6089/41702096@2b0a78f5

Higher-Order Functions (HOF)

A function which takes a function as an argument and/or returns a function.

valfilter= (predicate:Int=>Boolean,xs:List[Int])=> xs.filter(predicate)// filter: (Int => Boolean, List[Int]) => List[Int] = $$Lambda$6101/1664822486@6c2961d4
valisEven= (x:Int)=> x%2==0// isEven: Int => Boolean = $$Lambda$6102/1380731259@7caf5594
filter(isEven,List(1,2,3,4,5))// res0: List[Int] = List(2, 4)

Partial Application

Partially applying a function means creating a new function by pre-filling some of the arguments to the original function.

// Something to applyvaladd3= (a:Int,b:Int,c:Int)=> a+ b+ c// add3: (Int, Int, Int) => Int = $$Lambda$6104/749395786@26f51ccc// Partially applying `2` and `3` to `add3` gives you a one-argument functionvalfivePlus= add3(2,3,_:Int)// (c) => 2 + 3 + c// fivePlus: Int => Int = $$Lambda$6105/747846882@57c90a91fivePlus(4)// res3: Int = 9

Partial application helps create simpler functions from more complex ones by baking in data when you have it.Curried functions are automatically partially applied.

Currying

The process of converting a function that takes multiple arguments into a function that takes them one at a time.

Each time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed.

valsum= (a :Int,b:Int)=> a+ b// sum: (Int, Int) => Int = $$Lambda$6106/477864989@f720751valcurriedSum= (a:Int)=> (b:Int)=> a+ b// curriedSum: Int => (Int => Int) = $$Lambda$6107/1895392220@447d87e6curriedSum(40)(2)// 42.// res4: Int = 42valadd2= curriedSum(2)// (b) => 2 + b// add2: Int => Int = $$Lambda$6108/1784411761@45922de3add2(10)// 12// res5: Int = 12

Closure

A closure is a way of accessing a variable outside its scope.Formally, a closure is a technique for implementing lexically scoped named binding. It is a way of storing a function with an environment.

A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined.ie. they allow referencing a scope after the block in which the variables were declared has finished executing.

valaddTo= (x:Int)=> (y:Int)=> x+ y// addTo: Int => (Int => Int) = $$Lambda$6109/741101144@c019bedvaladdToFive= addTo(5)// addToFive: Int => Int = $$Lambda$6110/1430362686@30d35a2daddToFive(3)// returns 8// res6: Int = 8

The functionaddTo() returns a function(internally calledadd()), lets store it in a variable calledaddToFive with a curried call having parameter 5.

Ideally, when the functionaddTo finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on callingaddToFive(). This means that the state of the functionaddTo is saved even after the block of code has finished executing, otherwise there is no way of knowing thataddTo was called asaddTo(5) and the value of x was set to 5.

Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure.

The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it).

Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.

A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.

Further reading/Sources

Auto Currying

Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated.

lodash & Ramda have acurry function that works this way.

valadd= (x:Int,y:Int)=> x+ y// add: (Int, Int) => Int = $$Lambda$6111/885864900@6fc805b3valcurriedAdd= add.curried// curriedAdd: Int => (Int => Int) = scala.Function2$$Lambda$3285/878350569@583d1436curriedAdd(2)// (y) => 2 + y// res7: Int => Int = scala.Function2$$Lambda$3286/1189535279@75c6a7a5curriedAdd(1)(2)// 3// res8: Int = 3

Further reading

Function Composition

The act of putting two functions together to form a third function where the output of one function is the input of the other.

defcompose[A,B,C](f:B=>C,g:A=>B)= (a:A)=> f(g(a))// Definition// compose: [A, B, C](f: B => C, g: A => B)A => CvalfloorAndToString= compose((x:Double)=> x.toString, math.floor)// Usage// floorAndToString: Double => String = $$Lambda$6114/392323038@14236e09floorAndToString(121.212121)// '121.0'// res9: String = 121.0

Continuation

At any given point in a program, the part of the code that's yet to be executed is known as a continuation.

defprintAsString(num:Int)= println(s"Given$num")// printAsString: (num: Int)UnitvalprintAsString= (num:Int)=> println(s"Given$num")// printAsString: Int => Unit = $$Lambda$6115/353404609@582dea2fvaladdOneAndContinue= (num:Int,cc:Int=>Any)=> {valresult= num+1  cc(result)}// addOneAndContinue: (Int, Int => Any) => Any = $$Lambda$6116/209832866@9488095addOneAndContinue(2, printAsString)// Given 3// res10: Any = ()

Continuations are often seen in asynchronous programming when the program needs to wait to receive data before it can continue. The response is often passed off to the rest of the program, which is the continuation, once it's been received.

defcontinueProgramWith(data:String)= {// Continues program with data}// continueProgramWith: (data: String)UnitdefreadFileAsync(file:String,cb: (Option[Throwable],String)=>Unit)= {}// readFileAsync: (file: String, cb: (Option[Throwable], String) => Unit)UnitreadFileAsync("path/to/file", (err, response)=> {if (err.isDefined) {// handle error    ()  }  continueProgramWith(response)})

Purity

A function is pure if the return value is only determined by itsinput values, and does not produce side effects.

valgreet= (name:String)=>s"Hi,${name}"// greet: String => String = $$Lambda$6118/976300008@d803871greet("Brianne")// res12: String = Hi, Brianne

As opposed to each of the following:

varname="Brianne"// name: String = Briannedefgreet= ()=>s"Hi,${name}"// greet: () => Stringgreet()// res13: String = Hi, Brianne

The above example's output is based on data stored outside of the function...

vargreeting:String= _// greeting: String = nullvalgreet= (name:String)=> {  greeting=s"Hi,${name}"}// greet: String => Unit = $$Lambda$6120/1120068379@6bf02320greet("Brianne")greeting// res15: String = Hi, Brianne

... and this one modifies state outside of the function.

Side effects

A function or expression is said to have a side effect if apart from returning a value, it interacts with (reads from or writes to) external mutable state.

importjava.util.Date// import java.util.DatedefdifferentEveryTime=newDate()// differentEveryTime: java.util.Date
println("IO is a side effect!")// IO is a side effect!

Idempotent

A function is idempotent if reapplying it to its result does not produce a different result.

f(f(x)) ≍ f(x)
math.abs(math.abs(10))// res17: Int = 10
defsort[A:Ordering](xs:List[A])= xs.sorted// sort: [A](xs: List[A])(implicit evidence$1: Ordering[A])List[A]sort(sort(sort(List(2,1))))// res18: List[Int] = List(1, 2)

Point-Free Style

Writing functions where the definition does not explicitly identify the arguments used. This style usually requirescurrying or otherHigher-Order functions. A.K.A Tacit programming.

// Givendefmap[A,B](fn:A=>B)= (list:List[A])=> list.map(fn)// map: [A, B](fn: A => B)List[A] => List[B]valadd= (a:Int)=> (b:Int)=> a+ b// add: Int => (Int => Int) = $$Lambda$6121/1340871739@61a102c5// Then// Not points-free - `numbers` is an explicit argumentvalincrementAll= (numbers:List[Int])=> map(add(1))(numbers)// incrementAll: List[Int] => List[Int] = $$Lambda$6122/1403313951@7e5972fd// Points-free - The list is an implicit argumentvalincrementAll2= map(add(1))// incrementAll2: List[Int] => List[Int] = $$Lambda$6124/221818483@221baf45

incrementAll identifies and uses the parameternumbers, so it is not points-free.incrementAll2 is written just by combining functions and values, making no mention of its arguments. Itis points-free.

Points-free function definitions look just like normal assignments withoutfunction or=>.

Predicate

A predicate is a function that returns true or false for a given value. A common use of a predicate is as the callback for array filter.

valpredicate= (a:Int)=> a>2// predicate: Int => Boolean = $$Lambda$6125/2085181758@1e842ab7List(1,2,3,4).filter(predicate)// res24: List[Int] = List(3, 4)

Contracts

A contract specifies the obligations and guarantees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated.

scala>// Define our contract : int -> int|defcontract[A](input:A):Boolean= inputmatch {|case_ :Int=>true|case _=>thrownewException("Contract violated: expected int -> int")| }contract: [A](input:A)Booleanscala>defaddOne[A](num:A):Int= {|   contract(num)|   num.asInstanceOf[Int]+1| }addOne: [A](num:A)Intscala> addOne(2)// 3res26:Int=3scala> addOne("some string")// Contract violated: expected int -> intjava.lang.Exception:Contractviolated: expected int-> int  at .contract(<console>:16)  at .addOne(<console>:15)  ...43 elided

Category

A category in category theory is a collection of objects and morphisms between them. In programming, typically typesact as the objects and functions as morphisms.

To be a valid category 3 rules must be met:

  1. There must be an identity morphism that maps an object to itself.Wherea is an object in some category,there must be a function froma -> a.
  2. Morphisms must compose.Wherea,b, andc are objects in some category,andf is a morphism froma -> b, andg is a morphism fromb -> c;g(f(x)) must be equivalent to(g • f)(x).
  3. Composition must be associativef • (g • h) is the same as(f • g) • h

Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things.

Further reading

Value

Anything that can be assigned to a variable.

caseclassPerson(name:String,age:Int)// defined class Person5// res28: Int = 5Person("John",30)// res29: Person = Person(John,30)(a:Any)=> a// res30: Any => Any = $$Lambda$6126/1828268232@117ca3b4List(1)// res31: List[Int] = List(1)null// res32: Null = null

Constant

A variable that cannot be reassigned once defined.

valfive=5// five: Int = 5valjohn=Person("John",30)// john: Person = Person(John,30)

Constants arereferentially transparent. That is, they can be replaced with the values that they represent without affecting the result.

With the above two constants the following expression will always returntrue.

john.age+ five==Person("John",30).age+5// res33: Boolean = true

Functor

An object that implements amap function which, while running over each value in the object to produce a new object, adheres to two rules:

Preserves identity

object.map(x => x) ≍ object

Composable

object.map(compose(f, g)) ≍ object.map(g).map(f)

(f,g are arbitrary functions)

A common functor in JavaScript isArray since it abides to the two functor rules:

List(1,2,3).map(x=> x)// res34: List[Int] = List(1, 2, 3)

and

valf= (x:Int)=> x+1// f: Int => Int = $$Lambda$6128/977330834@2ef88643valg= (x:Int)=> x*2// g: Int => Int = $$Lambda$6129/739719665@1b4dfd52List(1,2,3).map(x=> f(g(x)))// res35: List[Int] = List(3, 5, 7)List(1,2,3).map(g).map(f)// res36: List[Int] = List(3, 5, 7)

Pointed Functor

An Applicative with anpure function that putsany single value into it.

cats addsApplicative#pure making arrays a pointed functor.

importcats._// import cats._importcats.implicits._// import cats.implicits._Applicative[List].pure(1)// res37: List[Int] = List(1)

Lift

Lifting is when you take a value and put it into an object like afunctor. If you lift a function into anApplicative Functor then you can make it work on values that are also in that functor.

Some implementations have a function calledlift, orliftA2 to make it easier to run functions on functors.

defliftA2[F[_]:Monad,A,B,C](f:A=>B=>C)(a:F[A],b:F[B])= {  a.map(f).ap(b)}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// liftA2: [F[_], A, B, C](f: A => (B => C))(a: F[A], b: F[B])(implicit evidence$1: cats.Monad[F])F[C]valmult= (a:Int)=> (b:Int)=> a* b// mult: Int => (Int => Int) = $$Lambda$6131/1684188711@6840cae6valliftedMult= liftA2[List,Int,Int,Int](mult) _// liftedMult: (List[Int], List[Int]) => List[Int] = $$Lambda$6132/1015569705@69b98e8liftedMult(List(1,2),List(3))// res38: List[Int] = List(3, 6)liftA2((a:Int)=> (b:Int)=> a+ b)(List(1,2),List(3,4))// res39: List[Int] = List(4, 5, 5, 6)

Lifting a one-argument function and applying it does the same thing asmap.

valincrement= (x:Int)=> x+1// increment: Int => Int = $$Lambda$6137/1176025030@60dd7083Applicative[List].lift(increment)(List(2))// res40: List[Int] = List(3)List(2).map(increment)// res41: List[Int] = List(3)

Referential Transparency

An expression that can be replaced with its value without changing thebehavior of the program is said to be referentially transparent.

Say we have function greet:

valgreet= ()=>"Hello World!"// greet: () => String = $$Lambda$6139/1754785613@1d1c9e6a

Any invocation ofgreet() can be replaced withHello World! hence greet isreferentially transparent.

Equational Reasoning

When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.

Lambda

An anonymous function that can be treated like a value.

(_:Int)+1// res42: Int => Int = $$Lambda$6140/835760611@2344fbd6(x:Int)=> x+1// res43: Int => Int = $$Lambda$6141/605433877@12d4147c

Lambdas are often passed as arguments to Higher-Order functions.

List(1,2).map(_+1)// res44: List[Int] = List(2, 3)

You can assign a lambda to a variable.

valadd1= (a:Int)=> a+1// add1: Int => Int = $$Lambda$6143/1533951980@6546b471

Lambda Calculus

A branch of mathematics that uses functions to create auniversal model of computation.

Lazy evaluation

Lazy evaluation is a call-by-need evaluation mechanism that delays the evaluation of an expression until its value is needed. In functional languages, this allows for structures like infinite lists, which would not normally be available in an imperative language where the sequencing of commands is significant.

lazyvalrand:Double= {  println("generate random value...")  math.random()}// rand: Double = <lazy>
rand// Each execution gives a random value, expression is evaluated on need.// generate random value...// res45: Double = 0.7668030551457087

Monoid

An object with a function that "combines" that object with another of the same type.

One simple monoid is the addition of numbers:

1+1// res46: Int = 2

In this case number is the object and+ is the function.

An "identity" value must also exist that when combined with a value doesn't change it.

The identity value for addition is0.

1+0// res47: Int = 1

It's also required that the grouping of operations will not affect the result (associativity):

1+ (2+3)== (1+2)+3// res48: Boolean = true

Array concatenation also forms a monoid:

List(1,2):::List(3,4)// res49: List[Int] = List(1, 2, 3, 4)

The identity value is empty array[]

List(1,2):::List()// res50: List[Int] = List(1, 2)

If identity and compose functions are provided, functions themselves form a monoid:

defidentity[A](a:A):A= a// identity: [A](a: A)Adefcompose[A,B,C](f:B=>C,g:A=>B)= (a:A)=> f(g(a))// Definition// compose: [A, B, C](f: B => C, g: A => B)A => C

foo is any function that takes one argument.

compose(foo, identity) ≍ compose(identity, foo) ≍ foo

Monad

A monad is an object withpure andflatMap functions.flatMap is likemap except it un-nests the resulting nested object.

// ImplementationtraitMonad[F[_]] {defpure[A](a:A):F[A]defflatMap[A,B](fa:F[A])(f:A=>F[B]):F[B]defmap[A,B](fa:F[A])(f:A=>B):F[B]}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined trait Monad// warning: previously defined object Monad is not a companion to trait Monad.// Companions must be defined together; you may wish to use :paste mode for this.objectMonad {defapply[F[_]](implicitev:Monad[F])= evimplicitvallistInstance:Monad[List]=newMonad[List] {defpure[A](x:A)=List(x)defflatMap[A,B](fa:List[A])(f:A=>List[B]):List[B]=       fa.foldLeft(List[B]()) { (acc, x)=> acc::: f(x) }defmap[A,B](fa:List[A])(f:A=>B):List[B]=      flatMap(fa)(x=> pure(f(x)))        }}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined object Monad// warning: previously defined trait Monad is not a companion to object Monad.// Companions must be defined together; you may wish to use :paste mode for this.importMonad._// import Monad._// UsageMonad[List].flatMap(List("cat,dog","fish,bird"))(a=> a.split(",").toList)// res53: List[String] = List(cat, dog, fish, bird)// Contrast to mapMonad[List].map(List("cat,dog","fish,bird"))(a=> a.split(",").toList)// res55: List[List[String]] = List(List(cat, dog), List(fish, bird))

pure is also known asreturn in other functional languages.flatMap is also known asbind in other languages.

Comonad

An object that hasextract andcoflatMap functions.

traitComonad[F[_]] {defextract[A](x:F[A]):AdefcoflatMap[A,B](fa:F[A])(f:F[A]=>B):F[B]}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined trait Comonad// warning: previously defined object Comonad is not a companion to trait Comonad.// Companions must be defined together; you may wish to use :paste mode for this.typeId[X]=X// defined type alias Iddefid[X](x:X):Id[X]= x// id: [X](x: X)Id[X]objectComonad {defapply[F[_]](implicitev:Comonad[F])= evimplicitvalidInstance:Comonad[Id]=newComonad[Id] {defextract[A](x:Id[A]):A= xdefcoflatMap[A,B](fa:Id[A])(f:Id[A]=>B):Id[B]= {      id(f(fa))    }  }}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined object Comonad// warning: previously defined trait Comonad is not a companion to object Comonad.// Companions must be defined together; you may wish to use :paste mode for this.

Extract takes a value out of a functor.

importComonad._// import Comonad._Comonad[Id].extract(id(1))// res56: Id[Int] = 1

Extend runs a function on the comonad. The function should return the same type as the comonad.

Comonad[Id].coflatMap[Int,Int](id(1))(co=>Comonad[Id].extract(co)+1)// res57: Id[Int] = 2

Applicative Functor

An applicative functor is an object with anap function.ap applies a function in the object to a value in another object of the same type.

// ImplementationtraitApplicative[F[_]] {defap[A,B](ff:F[A=>B])(fa:F[A]):F[B]}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined trait Applicative// warning: previously defined object Applicative is not a companion to trait Applicative.// Companions must be defined together; you may wish to use :paste mode for this.objectApplicative {defapply[F[_]](implicitev:Applicative[F])= evimplicitvallistInstance=newApplicative[List] {defap[A,B](ff:List[A=>B])(fa:List[A]):List[B]=      ff.foldLeft(List[B]()) { (acc, f)=> acc::: fa.map(f) }  }}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined object Applicative// warning: previously defined trait Applicative is not a companion to object Applicative.// Companions must be defined together; you may wish to use :paste mode for this.importApplicative._// import Applicative._// Example usageApplicative[List].ap(List((_:Int)+1))(List(1))// res60: List[Int] = List(2)

This is useful if you have two objects and you want to apply a binary function to their contents.

// Arrays that you want to combinevalarg1=List(1,3)// arg1: List[Int] = List(1, 3)valarg2=List(4,5)// arg2: List[Int] = List(4, 5)// combining function - must be curried for this to workvaladd= (x:Int)=> (y:Int)=> x+ y// add: Int => (Int => Int) = $$Lambda$6151/266874536@144646d8valpartiallyAppiedAdds=Applicative[List].ap(List(add))(arg1)// [(y) => 1 + y, (y) => 3 + y]// partiallyAppiedAdds: List[Int => Int] = List($$Lambda$6152/226672465@6ff3ff0, $$Lambda$6152/226672465@677536aa)

This gives you an array of functions that you can callap on to get the result:

Applicative[List].ap(partiallyAppiedAdds)(arg2)// res63: List[Int] = List(5, 6, 7, 8)

Morphism

A transformation function.

Endomorphism

A function where the input type is the same as the output.

// uppercase :: String -> Stringvaluppercase= (str:String)=> str.toUpperCase// uppercase: String => String = $$Lambda$6153/1625244377@4f348849// decrement :: Number -> Numbervaldecrement= (x:Int)=> x-1// decrement: Int => Int = $$Lambda$6154/147034451@797635f9

Isomorphism

A pair of transformations between 2 types of objects that is structural in nature and no data is lost.

For example, 2D coordinates could be stored as an array[2,3] or object{x: 2, y: 3}.

// Providing functions to convert in both directions makes them isomorphic.caseclassCoords(x:Int,y:Int)// defined class CoordsvalpairToCoords= (pair: (Int,Int))=>Coords(pair._1, pair._2)// pairToCoords: ((Int, Int)) => Coords = $$Lambda$6155/416347946@4d78afeavalcoordsToPair= (coods:Coords)=> (coods.x, coods.y)// coordsToPair: Coords => (Int, Int) = $$Lambda$6156/905411695@26eed67acoordsToPair(pairToCoords((1,2)))// res67: (Int, Int) = (1,2)pairToCoords(coordsToPair(Coords(1,2)))// res68: Coords = Coords(1,2)

Setoid

An object that has anequals function which can be used to compare other objects of the same type.

Make array a setoid:

traitEq[A] {defeqv(x:A,y:A):Boolean}// defined trait EqobjectEq {defapply[A](implicitev:Eq[A])= evimplicitdefarrayInstance[B]:Eq[Array[B]]=newEq[Array[B]] {defeqv(xs:Array[B],ys:Array[B]):Boolean=      xs.zip(ys).foldLeft(true) {case (isEq, (x, y))=> isEq&& x== y      }  }implicitclassEqOps[A](x:A) {defeqv(y:A)(implicitev:Eq[A])=      ev.eqv(x, y)  }}// defined object Eq// warning: previously defined trait Eq is not a companion to object Eq.// Companions must be defined together; you may wish to use :paste mode for this.importEq._// import Eq._Array(1,2)==Array(1,2)// res69: Boolean = falseArray(1,2).eqv(Array(1,2))// res70: Boolean = trueArray(1,2).eqv(Array(0))// res71: Boolean = false

Semigroup

An object that has acombine function that combines it with another object of the same type.

traitSemigroup[A] {defcombine(x:A,y:A):A}// defined trait SemigroupobjectSemigroup {defapply[A](implicitev:Semigroup[A])= evimplicitdeflistInstance[B]:Semigroup[List[B]]=newSemigroup[List[B]] {defcombine(x:List[B],y:List[B]):List[B]= x::: y  }implicitclassSemigroupOps[A](x:A) {defcombine(y:A)(implicitev:Semigroup[A]):A= ev.combine(x, y)  }}// defined object Semigroup// warning: previously defined trait Semigroup is not a companion to object Semigroup.// Companions must be defined together; you may wish to use :paste mode for this.importSemigroup._// import Semigroup._Semigroup[List[Int]].combine(List(1),List(2))// res0: List[Int] = List(1, 2)

Semigroup must be closed under associativity and arbitrary products.(x·y)·z = x·(y·z) for all x, y and z in the semigroup.

List(1).combine(List(2)).combine(List(3))// res1: List[Int] = List(1, 2, 3)List(1).combine(List(2).combine(List(3)))// res2: List[Int] = List(1, 2, 3)

Foldable

An object that has afoldr/l function that can transform that object into some other type.

traitFoldable[F[_]] {deffoldLeft[A,B](fa:F[A],b:B)(f: (B,A)=>B):BdeffoldRight[A,B](fa:F[A],b:B)(f: (A,B)=>B):B}// warning: there was one feature warning; for details, enable `:setting -feature' or `:replay -feature'// defined trait FoldableobjectFoldable {defapply[F[_]](implicitev:Foldable[F])= evimplicitvallistInstance=newFoldable[List]{deffoldLeft[A,B](fa:List[A],b:B)(f: (B,A)=>B):B= famatch {case x:: xs=> foldLeft(xs, f(b, x))(f)caseNil=> b     }deffoldRight[A,B](fa:List[A],b:B)(f: (A,B)=>B):B= famatch {case x:: xs=> f(x, foldRight(xs, b)(f))caseNil=> b    }  }}// defined object FoldableimportFoldable._// import Foldable._defsum[A](xs:List[A])(implicitN:Numeric[A]):A=Foldable[List].foldLeft(xs,N.zero) {case (acc, x)=>N.plus(acc, x)  }// sum: [A](xs: List[A])(implicit N: Numeric[A])Asum(List(1,2,3))// res3: Int = 6

Lens

A lens is a structure (often an object or function) that pairs a getter and a non-mutating setter for some other datastructure.

importcats.Functor// import cats.Functorimportmonocle.PLens// import monocle.PLensimportmonocle.Lens// import monocle.Lens// Using [Monocle's lens](https://github.com/julien-truffaut/Monocle)// S the source of a PLens// T the modified source of a PLens// A the target of a PLens// B the modified target of a PLensabstractclassPLens[S,T,A,B] {/** get the target of a PLens*/defget(s:S):A/** set polymorphically the target of a PLens using a function*/defset(b:B):S=>T/** modify polymorphically the target of a PLens using Functor function*/defmodifyF[F[_]:Functor](f:A=>F[B])(s:S):F[T]/** modify polymorphically the target of a PLens using a function*/defmodify(f:A=>B):S=>T}// defined class PLens// warning: previously defined object PLens is not a companion to class PLens.// Companions must be defined together; you may wish to use :paste mode for this.objectLens {/** alias for [[PLens]] apply with a monomorphic set function*/defapply[S,A](get:S=>A)(set:A=>S=>S):Lens[S,A]=PLens(get)(set)}// defined object LenscaseclassPerson(name:String)// defined class PersonvalnameLens=Lens[Person,String](_.name)(str=> p=> p.copy(name= str))// nameLens: monocle.Lens[Person,String] = monocle.PLens$$anon$8@5b2aa650

Having the pair of get and set for a given data structure enables a few key features.

valperson=Person("Gertrude Blanch")// person: Person = Person(Gertrude Blanch)// invoke the getter// get :: Person => StringnameLens.get(person)// res12: String = Gertrude Blanch// invoke the setter// set :: String => Person => PersonnameLens.set("Shafi Goldwasser")(person)// res15: Person = Person(Shafi Goldwasser)// run a function on the value in the structure// modify :: (String => String) => Person => PersonnameLens.modify(_.toUpperCase)(person)// res18: Person = Person(GERTRUDE BLANCH)

Lenses are also composable. This allows easy immutable updates to deeply nested data.

// This lens focuses on the first item in a non-empty arraydeffirstLens[A]=Lens[List[A],A] {// get first item in array  _.head} {// non-mutating setter for first item in array  x=> xs=> x:: xs.tail}// firstLens: [A]=> monocle.Lens[List[A],A]valpeople=List(Person("Gertrude Blanch"),Person("Shafi Goldwasser"))// people: List[Person] = List(Person(Gertrude Blanch), Person(Shafi Goldwasser))// Despite what you may assume, lenses compose left-to-right.(firstLens composeLens nameLens).modify(_.toUpperCase)(people)// res22: List[Person] = List(Person(GERTRUDE BLANCH), Person(Shafi Goldwasser))

Other implementations:

  • Quicklens - Modify deeply nested case class fields
  • Sauron - Yet another Scala lens macro, Lightweight lens library in less than 50-lines of Scala
  • scalaz.Lens

Type Signatures

Every functions in Scala will indicate the types of their arguments and return values.

// functionName :: firstArgType -> secondArgType -> returnType// add :: Number -> Number -> Numbervaladd= (x:Int)=> (y:Int)=> x+ y// add: Int => (Int => Int) = $$Lambda$6168/450833074@b76efce// increment :: Number -> Numbervalincrement= (x:Int)=> x+1// increment: Int => Int = $$Lambda$6169/2134951565@23429781

If a function accepts another function as an argument it is wrapped in parentheses.

// call :: (a -> b) -> a -> bdefcall[A,B]= (f:A=>B)=> (x:A)=> f(x)// call: [A, B]=> (A => B) => (A => B)

The lettersa,b,c,d are used to signify that the argument can be of any type. The following version ofmap takes a function that transforms a value of some typea into another typeb, an array of values of typea, and returns an array of values of typeb.

// map :: (a -> b) -> [a] -> [b]defmap[A,B]= (f:A=>B)=> (list:List[A])=> list.map(f)// map: [A, B]=> (A => B) => (List[A] => List[B])

Further reading

Algebraic data type

A composite type made from putting other types together. Two common classes of algebraic types aresum andproduct.

Sum type

A Sum type is the combination of two types together into another one. It is called sum because the number of possible values in the result type is the sum of the input types.

we can usesealed trait orEither to have this type:

// imagine that rather than sets here we have types that can only have these valuessealedtraitBool// defined trait BoolobjectTrueextendsBool// defined object TrueobjectFalseextendsBool// defined object FalsesealedtraitHalfTrue// defined trait HalfTrueobjectHalfTrueextendsHalfTrue// defined object HalfTrue// warning: previously defined trait HalfTrue is not a companion to object HalfTrue.// Companions must be defined together; you may wish to use :paste mode for this.// The weakLogic type contains the sum of the values from bools and halfTruetypeWeakLogicType=Either[Bool,HalfTrue]// defined type alias WeakLogicTypevalweakLogicValues:Set[Either[HalfTrue,Bool]]=Set(Right(True),Right(False),Left(HalfTrue))// weakLogicValues: Set[Either[HalfTrue,Bool]] = Set(Right(True$@c8afbd6), Right(False$@78d0f039), Left(HalfTrue$@76907679))

Sum types are sometimes called union types, discriminated unions, or tagged unions.

There's acouplelibraries in JS which help with defining and using union types.

Flow includesunion types and TypeScript hasEnums to serve the same role.

Product type

Aproduct type combines types together in a way you're probably more familiar with:

// point :: (Number, Number) -> {x: Number, y: Number}caseclassPoint(x:Int,y:Int)// defined class Pointvalpoint= (x:Int,y:Int)=>Point(x, y)// point: (Int, Int) => Point = $$Lambda$6170/1963675584@55a1298b

It's called a product because the total possible values of the data structure is the product of the different values. Many languages have a tuple type which is the simplest formulation of a product type.

See alsoSet theory.

Option

Option is asum type with two cases often calledSome andNone.

Option is useful for composing functions that might not return a value.

// Naive definitiontraitMyOption[+A] {defmap[B](f:A=>B):MyOption[B]defflatMap[B](f:A=>MyOption[B]):MyOption[B]}// defined trait MyOptioncaseclassMySome[A](a:A)extendsMyOption[A] {defmap[B](f:A=>B):MyOption[B]=MySome(f(a))defflatMap[B](f:A=>MyOption[B]):MyOption[B]= f(a)}// defined class MySomecaseobjectMyNoneextendsMyOption[Nothing] {defmap[B](f:Nothing=>B):MyOption[B]=thisdefflatMap[B](f:Nothing=>MyOption[B])=this}// defined object MyNone// maybeProp :: (String, {a}) -> Option adefmaybeProp[A,B](key:A,obj:Map[A,B]):Option[B]= obj.get(key)// maybeProp: [A, B](key: A, obj: Map[A,B])Option[B]

UseflatMap to sequence functions that returnOptions

// getItem :: Cart -> Option CartItemdefgetItem[A](cart:Map[String,Map[String,A]]):Option[Map[String,A]]= maybeProp("item", cart)// getItem: [A](cart: Map[String,Map[String,A]])Option[Map[String,A]]// getPrice :: Item -> Option NumberdefgetPrice[A](item:Map[String,A]):Option[A]= maybeProp("price", item)// getPrice: [A](item: Map[String,A])Option[A]// getNestedPrice :: cart -> Option adefgetNestedPrice[A](cart:Map[String,Map[String,A]])= getItem(cart).flatMap(getPrice)// getNestedPrice: [A](cart: Map[String,Map[String,A]])Option[A]getNestedPrice(Map())// res38: Option[Nothing] = NonegetNestedPrice(Map("item"->Map("foo"->1)))// res39: Option[Int] = NonegetNestedPrice(Map("item"->Map("price"->9.99)))// res40: Option[Double] = Some(9.99)

Option is also known asMaybe.Some is sometimes calledJust.None is sometimes calledNothing.

Functional Programming Libraries in Scala


P.S: This repo is successful due to the wonderfulcontributions!

About

Scala code examples - Jargon from the functional programming world in simple terms!

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Scala100.0%

[8]ページ先頭

©2009-2025 Movatter.jp