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

Jargon from the functional programming world in simple terms!

License

NotificationsYou must be signed in to change notification settings

hemanth/functional-programming-jargon

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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 JavaScript (ES2015).Why JavaScript?

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.

constsum=(a,b)=>a+b// The arity of sum is 2 (binary)constinc=a=>a+1// The arity of inc is 1 (unary)constzero=()=>0// The arity of zero is 0 (nullary)

Further reading

Higher-Order Functions (HOF)

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

constfilter=(predicate,xs)=>xs.filter(predicate)
constis=(type)=>(x)=>Object(x)instanceoftype
filter(is(Number),[0,'1',2,null])// [0, 2]

Closure

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.This allows the values in the closure to be accessed by returned functions.

constaddTo=x=>y=>x+yconstaddToFive=addTo(5)addToFive(3)// => 8

In this case thex is retained inaddToFive's closure with the value5.addToFive can then be called with theyto get back the sum.

Further reading/Sources

Partial Application

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

// Helper to create partially applied functions// Takes a function and some argumentsconstpartial=(f, ...args)=>// returns a function that takes the rest of the arguments(...moreArgs)=>// and calls the original function with all of themf(...args, ...moreArgs)// Something to applyconstadd3=(a,b,c)=>a+b+c// Partially applying `2` and `3` to `add3` gives you a one-argument functionconstfivePlus=partial(add3,2,3)// (c) => 2 + 3 + cfivePlus(4)// 9

You can also useFunction.prototype.bind to partially apply a function in JS:

constadd1More=add3.bind(null,2,3)// (c) => 2 + 3 + c

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.

constsum=(a,b)=>a+bconstcurriedSum=(a)=>(b)=>a+bcurriedSum(40)(2)// 42.constadd2=curriedSum(2)// (b) => 2 + badd2(10)// 12

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.

constadd=(x,y)=>x+yconstcurriedAdd=_.curry(add)curriedAdd(1,2)// 3curriedAdd(1)// (y) => 1 + ycurriedAdd(1)(2)// 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. This is one of the most important ideas of functional programming.

constcompose=(f,g)=>(a)=>f(g(a))// DefinitionconstfloorAndToString=compose((val)=>val.toString(),Math.floor)// UsagefloorAndToString(121.212121)// '121'

Continuation

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

constprintAsString=(num)=>console.log(`Given${num}`)constaddOneAndContinue=(num,cc)=>{constresult=num+1cc(result)}addOneAndContinue(2,printAsString)// 'Given 3'

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.

constcontinueProgramWith=(data)=>{// Continues program with data}readFileAsync('path/to/file',(err,response)=>{if(err){// handle errorreturn}continueProgramWith(response)})

Pure Function

A function is pure if the return value is only determined by its input values, and does not produce side effects. The function must always return the same result when given the same input.

constgreet=(name)=>`Hi,${name}`greet('Brianne')// 'Hi, Brianne'

As opposed to each of the following:

window.name='Brianne'constgreet=()=>`Hi,${window.name}`greet()// "Hi, Brianne"

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

letgreetingconstgreet=(name)=>{greeting=`Hi,${name}`}greet('Brianne')greeting// "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.

constdifferentEveryTime=newDate()
console.log('IO is a side effect!')

Idempotence

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

Math.abs(Math.abs(10))
sort(sort(sort([2,1])))

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.

// Givenconstmap=(fn)=>(list)=>list.map(fn)constadd=(a)=>(b)=>a+b// Then// Not point-free - `numbers` is an explicit argumentconstincrementAll=(numbers)=>map(add(1))(numbers)// Point-free - The list is an implicit argumentconstincrementAll2=map(add(1))

Point-free function definitions look just like normal assignments withoutfunction or=>. It's worth mentioning that point-free functions are not necessarily better than their counterparts, as they can be more difficult to understand when complex.

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.

constpredicate=(a)=>a>2;[1,2,3,4].filter(predicate)// [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.

// Define our contract : int -> booleanconstcontract=(input)=>{if(typeofinput==='number')returntruethrownewError('Contract violated: expected int -> boolean')}constaddOne=(num)=>contract(num)&&num+1addOne(2)// 3addOne('some string')// Contract violated: expected int -> boolean

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, three 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.

As an example we can define a category Max as a class:

classMax{constructor(a){this.a=a}id(){returnthis}compose(b){returnthis.a>b.a ?this :b}toString(){return`Max(${this.a})`}}newMax(2).compose(newMax(3)).compose(newMax(5)).id().id()// => Max(5)

Further reading

Value

Anything that can be assigned to a variable.

5Object.freeze({name:'John',age:30})// The `freeze` function enforces immutability.;(a)=>a;[1]undefined

Constant

A variable that cannot be reassigned once defined.

constfive=5constjohn=Object.freeze({name:'John',age: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===({name:'John',age:30}).age+5

Constant Function

Acurried function that ignores its second argument:

constconstant=a=>()=>a;[1,2].map(constant(0))// => [0, 0]

Constant Functor

Object whosemap doesn't transform the contents. SeeFunctor.

Constant(1).map(n=>n+1)// => Constant(1)

Constant Monad

Object whosechain doesn't transform the contents. SeeMonad.

Constant(1).chain(n=>Constant(n+1))// => Constant(1)

Functor

An object that implements amap function that takes a function which is run on the contents of that object. A functor must adhere to two rules:

Preserves identity

object.map(x=>x)

is equivalent to justobject.

Composable

object.map(x=>g(f(x)))

is equivalent to

object.map(f).map(g)

(f,g are arbitrary composable functions)

The reference implementation ofOption is a functor as it satisfies the rules:

Some(1).map(x=>x)// = Some(1)

and

constf=x=>x+1constg=x=>x*2Some(1).map(x=>g(f(x)))// = Some(4)Some(1).map(f).map(g)// = Some(4)

Pointed Functor

An object with anof function that putsany single value into it.

ES2015 addsArray.of making arrays a pointed functor.

Array.of(1)// [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.

constliftA2=(f)=>(a,b)=>a.map(f).ap(b)// note it's `ap` and not `map`.constmult=a=>b=>a*bconstliftedMult=liftA2(mult)// this function now works on functors like arrayliftedMult([1,2],[3])// [3, 6]liftA2(a=>b=>a+b)([1,2],[30,40])// [31, 41, 32, 42]

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

constincrement=(x)=>x+1lift(increment)([2])// [3];[2].map(increment)// [3]

Lifting simple values can be simply creating the object.

Array.of(1)// => [1]

Referential Transparency

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

Given the function greet:

constgreet=()=>'Hello World!'

Any invocation ofgreet() can be replaced withHello World! hence greet isreferentially transparent. This would be broken if greet depended on externalstate like configuration or a database call. See alsoPure Function andEquational Reasoning.

Equational Reasoning

When an application is composed of expressions and devoid of side effects,truths about the system can be derived from the parts. You can also be confidentabout details of your system without having to go through every function.

constgrainToDogs=compose(chickenIntoDogs,grainIntoChicken)constgrainToCats=compose(dogsIntoCats,grainToDogs)

In the example above, if you know thatchickenIntoDogs andgrainIntoChickenarepure then you know that the composition is pure. This can be taken furtherwhen more is known about the functions (associative, commutative, idempotent, etc...).

Lambda

An anonymous function that can be treated like a value.

;(function(a){returna+1});(a)=>a+1

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

;[1,2].map((a)=>a+1)// [2, 3]

You can assign a lambda to a variable:

constadd1=(a)=>a+1

Lambda Calculus

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

Functional Combinator

A higher-order function, usually curried, which returns a new function changed in some way. Functional combinators are often used inPoint-Free Style to write especially terse programs.

// The "C" combinator takes a curried two-argument function and returns one which calls the original function with the arguments reversed.constC=(f)=>(a)=>(b)=>f(b)(a)constdivide=(a)=>(b)=>a/bconstdivideBy=C(divide)constdivBy10=divideBy(10)divBy10(30)// => 3

See alsoList of Functional Combinators in JavaScript which includes links to more references.

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.

constrand=function*(){while(1<2){yieldMath.random()}}
constrandIter=rand()randIter.next()// Each execution gives a random value, expression is evaluated on need.

Monoid

An object with a function that "combines" that object with another of the same type (semigroup) which has an "identity" value.

One simple monoid is the addition of numbers:

1+1// 2

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

When any value is combined with the "identity" value the result must be the original value. The identity must also be commutative.

The identity value for addition is0.

1+0// 10+1// 11+0===0+1

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

1+(2+3)===(1+2)+3// true

Array concatenation also forms a monoid:

;[1,2].concat([3,4])// [1, 2, 3, 4]

The identity value is empty array[]:

;[1,2].concat([])// [1, 2]

As a counterexample, subtraction does not form a monoid because there is no commutative identity value:

0-4===4-0// false

Monad

A monad is an object withof andchain functions.chain is likemap except it un-nests the resulting nested object.

// ImplementationArray.prototype.chain=function(f){returnthis.reduce((acc,it)=>acc.concat(f(it)),[])}// UsageArray.of('cat,dog','fish,bird').chain((a)=>a.split(','))// ['cat', 'dog', 'fish', 'bird']// Contrast to mapArray.of('cat,dog','fish,bird').map((a)=>a.split(','))// [['cat', 'dog'], ['fish', 'bird']]

of is also known asreturn in other functional languages.chain is also known asflatmap andbind in other languages.

Comonad

An object that hasextract andextend functions.

constCoIdentity=(v)=>({val:v,extract(){returnthis.val},extend(f){returnCoIdentity(f(this))}})

extract takes a value out of a functor:

CoIdentity(1).extract()// 1

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

CoIdentity(1).extend((co)=>co.extract()+1)// CoIdentity(2)

Kleisli Composition

An operation for composing twomonad-returning functions (Kleisli Arrows) where they have compatible types. In Haskell this is the>=> operator.

UsingOption:

// safeParseNum :: String -> Option NumberconstsafeParseNum=(b)=>{constn=parseNumber(b)returnisNaN(n) ?None() :Some(n)}// validatePositive :: Number -> Option NumberconstvalidatePositive=(a)=>a>0 ?Some(a) :None()// kleisliCompose :: Monad M => ((b -> M c), (a -> M b)) -> a -> M cconstkleisliCompose=(g,f)=>(x)=>f(x).chain(g)// parseAndValidate :: String -> Option NumberconstparseAndValidate=kleisliCompose(validatePositive,safeParseNum)parseAndValidate('1')// => Some(1)parseAndValidate('asdf')// => NoneparseAndValidate('999')// => Some(999)

This works because:

  • option is amonad,
  • bothvalidatePositive andsafeParseNum return the same kind of monad (Option),
  • the type ofvalidatePositive's argument matchessafeParseNum's unwrapped return.

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.

// ImplementationArray.prototype.ap=function(xs){returnthis.reduce((acc,f)=>acc.concat(xs.map(f)),[])}// Example usage;[(a)=>a+1].ap([1])// [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 combineconstarg1=[1,3]constarg2=[4,5]// combining function - must be curried for this to workconstadd=(x)=>(y)=>x+yconstpartiallyAppliedAdds=[add].ap(arg1)// [(y) => 1 + y, (y) => 3 + y]

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

partiallyAppliedAdds.ap(arg2)// [5, 6, 7, 8]

Morphism

A relationship between objects within acategory. In the context of functional programming all functions are morphisms.

Homomorphism

A function where there is a structural property that is the same in the input as well as the output.

For example, in aMonoid homomorphism both the input and the output are monoids even if their types are different.

// toList :: [number] -> stringconsttoList=(a)=>a.join(', ')

toList is a homomorphism because:

  • array is a monoid - has aconcat operation and an identity value ([]),
  • string is a monoid - has aconcat operation and an identity value ('').

In this way, a homomorphism relates to whatever property you care about in the input and output of a transformation.

Endomorphisms andIsomorphisms are examples of homomorphisms.

Further Reading

Endomorphism

A function where the input type is the same as the output. Since the types are identical, endomorphisms are alsohomomorphisms.

// uppercase :: String -> Stringconstuppercase=(str)=>str.toUpperCase()// decrement :: Number -> Numberconstdecrement=(x)=>x-1

Isomorphism

A morphism made of 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 the 2D coordinate structures isomorphic.constpairToCoords=(pair)=>({x:pair[0],y:pair[1]})constcoordsToPair=(coords)=>[coords.x,coords.y]coordsToPair(pairToCoords([1,2]))// [1, 2]pairToCoords(coordsToPair({x:1,y:2}))// {x: 1, y: 2}

Isomorphisms are an interesting example ofmorphism because more than single function is necessary for it to be satisfied. Isomorphisms are alsohomomorphisms since both input and output types share the property of being reversible.

Catamorphism

A function which deconstructs a structure into a single value.reduceRight is an example of a catamorphism for array structures.

// sum is a catamorphism from [Number] -> Numberconstsum=xs=>xs.reduceRight((acc,x)=>acc+x,0)sum([1,2,3,4,5])// 15

Anamorphism

A function that builds up a structure by repeatedly applying a function to its argument.unfold is an example which generates an array from a function and a seed value. This is the opposite of acatamorphism. You can think of this as an anamorphism builds up a structure and catamorphism breaks it down.

constunfold=(f,seed)=>{functiongo(f,seed,acc){constres=f(seed)returnres ?go(f,res[1],acc.concat([res[0]])) :acc}returngo(f,seed,[])}
constcountDown=n=>unfold((n)=>{returnn<=0 ?undefined :[n,n-1]},n)countDown(5)// [5, 4, 3, 2, 1]

Hylomorphism

The function which composes ananamorphism followed by acatamorphism.

constsumUpToX=(x)=>sum(countDown(x))sumUpToX(5)// 15

Paramorphism

A function just likereduceRight. However, there's a difference:

In paramorphism, your reducer's arguments are the current value, the reduction of all previous values, and the list of values that formed that reduction.

// Obviously not safe for lists containing `undefined`,// but good enough to make the point.constpara=(reducer,accumulator,elements)=>{if(elements.length===0){returnaccumulator}consthead=elements[0]consttail=elements.slice(1)returnreducer(head,tail,para(reducer,accumulator,tail))}constsuffixes=list=>para((x,xs,suffxs)=>[xs, ...suffxs],[],list)suffixes([1,2,3,4,5])// [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []]

The third parameter in the reducer (in the above example,[x, ... xs]) is kind of like having a history of what got you to your current acc value.

Apomorphism

The opposite of paramorphism, just as anamorphism is the opposite of catamorphism. With paramorphism, you retain access to the accumulator and what has been accumulated, apomorphism lets youunfold with the potential to return early.

Setoid

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

Make array a setoid:

Array.prototype.equals=function(arr){constlen=this.lengthif(len!==arr.length){returnfalse}for(leti=0;i<len;i++){if(this[i]!==arr[i]){returnfalse}}returntrue};[1,2].equals([1,2])// true;[1,2].equals([0])// false

Semigroup

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

;[1].concat([2])// [1, 2]

Foldable

An object that has areduce function that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

constsum=(list)=>list.reduce((acc,val)=>acc+val,0)sum([1,2,3])// 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.

// Using [Ramda's lens](http://ramdajs.com/docs/#lens)constnameLens=R.lens(// getter for name property on an object(obj)=>obj.name,// setter for name property(val,obj)=>Object.assign({},obj,{name:val}))

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

constperson={name:'Gertrude Blanch'}// invoke the getterR.view(nameLens,person)// 'Gertrude Blanch'// invoke the setterR.set(nameLens,'Shafi Goldwasser',person)// {name: 'Shafi Goldwasser'}// run a function on the value in the structureR.over(nameLens,uppercase,person)// {name: '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 arrayconstfirstLens=R.lens(// get first item in arrayxs=>xs[0],// non-mutating setter for first item in array(val,[__, ...xs])=>[val, ...xs])constpeople=[{name:'Gertrude Blanch'},{name:'Shafi Goldwasser'}]// Despite what you may assume, lenses compose left-to-right.R.over(compose(firstLens,nameLens),uppercase,people)// [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]

Other implementations:

Type Signatures

Often functions in JavaScript will include comments that indicate the types of their arguments and return values.

There's quite a bit of variance across the community, but they often follow the following patterns:

// functionName :: firstArgType -> secondArgType -> returnType// add :: Number -> Number -> Numberconstadd=(x)=>(y)=>x+y// increment :: Number -> Numberconstincrement=(x)=>x+1

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

// call :: (a -> b) -> a -> bconstcall=(f)=>(x)=>f(x)

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]constmap=(f)=>(list)=>list.map(f)

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.

JavaScript doesn't have types like this, but we can useSets to pretend:

// imagine that rather than sets here we have types that can only have these valuesconstbools=newSet([true,false])consthalfTrue=newSet(['half-true'])// The weakLogic type contains the sum of the values from bools and halfTrueconstweakLogicValues=newSet([...bools, ...halfTrue])

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}constpoint=(x,y)=>({ x, y})

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.

Further reading

Option

Option is asum type with two cases often calledSome andNone.

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

// Naive definitionconstSome=(v)=>({val:v,map(f){returnSome(f(this.val))},chain(f){returnf(this.val)}})constNone=()=>({map(f){returnthis},chain(f){returnthis}})// maybeProp :: (String, {a}) -> Option aconstmaybeProp=(key,obj)=>typeofobj[key]==='undefined' ?None() :Some(obj[key])

Usechain to sequence functions that returnOptions:

// getItem :: Cart -> Option CartItemconstgetItem=(cart)=>maybeProp('item',cart)// getPrice :: Item -> Option NumberconstgetPrice=(item)=>maybeProp('price',item)// getNestedPrice :: cart -> Option aconstgetNestedPrice=(cart)=>getItem(cart).chain(getPrice)getNestedPrice({})// None()getNestedPrice({item:{foo:1}})// None()getNestedPrice({item:{price:9.99}})// Some(9.99)

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

Function

Afunctionf :: A => B is an expression - often called arrow or lambda expression - withexactly one (immutable) parameter of typeA andexactly one return value of typeB. That value depends entirely on the argument, making functions context-independent, orreferentially transparent. What is implied here is that a function must not produce any hiddenside effects - a function is alwayspure, by definition. These properties make functions pleasant to work with: they are entirely deterministic and therefore predictable. Functions enable working with code as data, abstracting over behaviour:

// times2 :: Number -> Numberconsttimes2=n=>n*2;[1,2,3].map(times2)// [2, 4, 6]

Partial function

A partial function is afunction which is not defined for all arguments - it might return an unexpected result or may never terminate. Partial functions add cognitive overhead, they are harder to reason about and can lead to runtime errors. Some examples:

// example 1: sum of the list// sum :: [Number] -> Numberconstsum=arr=>arr.reduce((a,b)=>a+b)sum([1,2,3])// 6sum([])// TypeError: Reduce of empty array with no initial value// example 2: get the first item in list// first :: [A] -> Aconstfirst=a=>a[0]first([42])// 42first([])// undefined// or even worse:first([[42]])[0]// 42first([])[0]// Uncaught TypeError: Cannot read property '0' of undefined// example 3: repeat function N times// times :: Number -> (Number -> Number) -> Numberconsttimes=n=>fn=>n&&(fn(n),times(n-1)(fn))times(3)(console.log)// 3// 2// 1times(-1)(console.log)// RangeError: Maximum call stack size exceeded

Dealing with partial functions

Partial functions are dangerous as they need to be treated with great caution. You might get an unexpected (wrong) result or run into runtime errors. Sometimes a partial function might not return at all. Being aware of and treating all these edge cases accordingly can become very tedious.Fortunately a partial function can be converted to a regular (or total) one. We can provide default values or use guards to deal with inputs for which the (previously) partial function is undefined. Utilizing theOption type, we can yield eitherSome(value) orNone where we would otherwise have behaved unexpectedly:

// example 1: sum of the list// we can provide default value so it will always return result// sum :: [Number] -> Numberconstsum=arr=>arr.reduce((a,b)=>a+b,0)sum([1,2,3])// 6sum([])// 0// example 2: get the first item in list// change result to Option// first :: [A] -> Option Aconstfirst=a=>a.length ?Some(a[0]) :None()first([42]).map(a=>console.log(a))// 42first([]).map(a=>console.log(a))// console.log won't execute at all// our previous worst casefirst([[42]]).map(a=>console.log(a[0]))// 42first([]).map(a=>console.log(a[0]))// won't execute, so we won't have error here// more of that, you will know by function return type (Option)// that you should use `.map` method to access the data and you will never forget// to check your input because such check become built-in into the function// example 3: repeat function N times// we should make function always terminate by changing conditions:// times :: Number -> (Number -> Number) -> Numberconsttimes=n=>fn=>n>0&&(fn(n),times(n-1)(fn))times(3)(console.log)// 3// 2// 1times(-1)(console.log)// won't execute anything

Making your partial functions total ones, these kinds of runtime errors can be prevented. Always returning a value will also make for code that is both easier to maintain and to reason about.

Total Function

A function which returns a valid result for all inputs defined in its type. This is as opposed toPartial Functions which may throw an error, return an unexpected result, or fail to terminate.

Functional Programming Libraries in JavaScript


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

About

Jargon from the functional programming world in simple terms!

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp