- Notifications
You must be signed in to change notification settings - Fork8
Jargon from the functional programming world in simple terms!
License
jmesyou/functional-programming-jargon.py
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
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.
This is a fork ofFunctional Programming Jargon. Examples are presented in Python3.
This document attempts to adhere toPEP8 as best as possible.
This document is WIP and pull requests are welcome!
Translations
Table of Contents
- Arity
- Higher-Order Functions (HOF)
- Closure
- Partial Application
- Currying
- Auto Currying
- Function Composition
- Continuation
- Purity
- Side effects
- Idempotent
- Point-Free Style
- Predicate
- Contracts
- Category
- Value
- Constant
- Functor
- Pointed Functor
- Lift
- Referential Transparency
- Equational Reasoning
- Lambda
- Lambda Calculus
- Lazy evaluation
- Monoid
- Monad
- Comonad
- Applicative Functor
- Morphism
- Setoid
- Semigroup
- Foldable
- Lens
- Type Signatures
- Algebraic data type
- Option
- Function
- Partial function
- Functional Programming Libraries in Python
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).
frominspectimportsignatureadd=lambdaa,b:a+barity=len(signature(add).parameters)print(arity)# 2# The arity of add is 2
A function which takes a function as an argument and/or returns a function.
filter=lambdapredicate,xs: [xforxinxsifpredicate(xs)]
is_a=lambdaT:lambdax:type(x)isT
filter(is_a(int), [0,'1',2,None])# [0, 2]
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.
add_to=lambdax:lambday:x+yadd_to_five=add_to(5)add_to_five(3)# returns 8
The functionadd_to()
returns a function(internally calledadd()
), lets store it in a variable calledadd_to_five
with a curried call having parameter 5.
Ideally, when the functionadd_to
finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on callingadd_to_five()
. This means that the state of the functionadd_to
is saved even after the block of code has finished executing, otherwise there is no way of knowing thatadd_to
was called asadd_to(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
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 argumentspartial=lambdaf,*args:# returns a function that takes the rest of the argumentslambda*more_args:# and calls the original function with all of themf(args,more_args)# Something to applyadd3=lambdaa,b,c:a+b+c# Partially applying `2` and `3` to `add3` gives you a one-argument functionfive_plus=partial(add3,2,3)# (c) => 2 + 3 + cfive_plus(4)# 9
You can also usefunctools.partial
to partially apply a function in Python:
fromfunctoolsimportpartialadd_more=partial(add3,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.
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.
sum=lambdaa,b:a+bcurried_sum=lambdaa:lambdab:a+bcurried_sum(40)(2)# 42.add2=curried_sum(2)# (b) => 2 + badd2(10)# 12
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.
Thetoolz
module has an currying decorator which works this way
fromtoolzimportcurry@currydefadd(x,y):returnx+yadd(1,2)# 3add(1)# (y) => 1 + yadd(1)(2)# 3
Further reading
The act of putting two functions together to form a third function where the output of one function is the input of the other.
importmathcompose=lambdaf,g:lambdaa:f(g(a))# Definitionfloor_and_str=compose(str,Math.floor)# Usagefloor_and_string(121.212121)# '121'
At any given point in a program, the part of the code that's yet to be executed is known as a continuation.
print_as_string=lambdanum:print(num)# this was previously defined as multi-line function in Javascript# however, Python only supports single expression lambdasadd_one_and_continue=lambdanum,cc:cc(num+1)add_one_and_continue(2,print_as_string)# '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.
continue_program_with=lambdadata: ...# Continues program with dataread_file_async('path/to/file',lambdaerr,response:raiseerriferrelsecontinue_program_with(response))
A function is pure if the return value is only determined by itsinput values, and does not produce side effects.
greet=lambdaname:'Hi, {}'.format(name)greet('Brianne')# 'Hi, Brianne'
As opposed to each of the following:
name='Brianne'greet=lambda:'Hi, {}'.format(name)greet()# "Hi, Brianne"
The above example's output is based on data stored outside of the function...
greeting=Nonedefgreet(name):globalgreetinggreeting='Hi, {}'.format(name)greet('Brianne')greeting# "Hi, Brianne"
... and this one modifies state outside of the function.
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.
different_ever_time=list()
print('IO is a side effect!')
A function is idempotent if reapplying it to its result does not produce a different result.
f(f(x)) ≍ f(x)
importmathmath.abs(math.abs(10))
sorted(sorted(sorted([2,1])))
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.
# Givenmap=lambdafn:lambdaxs: [fn(x)forxinxs]add=lambdaa:lambdab:a+b# Then# Not points-free - `numbers` is an explicit argumentincrement_all=lambdanumbers:map(add(1))(numbers)# Points-free - The list is an implicit argumentincrement_all2=map(add(1))
increment_all
identifies and uses the parameternumbers
, so it is not points-free.increment_all2
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 withoutdef
orlambda
.
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.
predicate=lambdaa:a>2filter(predicate, [1,2,3,4])# [3, 4]
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.
defthrow(ex):raiseex# Define our contract : int -> booleancontract=lambdavalue:Trueiftype(value)isintelsethrow(Exception('Contract violated: expected int -> boolean'))add1=lambdanum:contract(num)andnum+1add1(2)# 3add1('some string')# Contract violated: expected int -> boolean
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:
- There must be an identity morphism that maps an object to itself.Where
a
is an object in some category,there must be a function froma -> a
. - Morphisms must compose.Where
a
,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)
. - Composition must be associative
f • (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
Anything that can be assigned to a variable.
fromcollectionsimportnamedtuplePerson=namedtuple('Person','name age')5Person('John',30)lambdaa:a[1]None
A variable that cannot be reassigned once defined.
five=5john=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
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)
Iterables in Python are functors since they abide by the two functor rules:
map(lambdax:x, [1,2,3])# = [1, 2, 3]map(lambdax:x, (1,2,3))# = (1, 2, 3)
and
f=lambdax:x+1g=lambdax:x*2map(lambdax:f(g(x)), [1,2,3])# = [3, 5, 7]map(f,map(g, [1,2,3]))# = [3, 5, 7]
An object with anof
function that putsany number of values into it. The following propertyof(f(x)) == of(x).map(f)
must also hold for any pointed functor.
We create a custom classArray
which mimics the original Javascript for a pointed functor.
classArray(list):of=lambda*args:Array([aforainargs])Array.of(1)# [1]
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.
# OSlash applicative library https://github.com/dbrattli/oslashfromoslashimportList,Applicative# we import the ApplicativeliftA2=lambdaf:lambdaa,b:a.map(f)*b# a, b is of type Applicative where (*) is the apply function.mult=lambdaa:lambdab:a*b# (*) is just regular multiplicationlifted_mult=liftA2(mult)# this function now works on functors like oslash.Listlifted_mult(List([1,2]),List([3]))# [3, 6]liftA2(lambdaa:lambdab:a+b)(List([1,2]),List([3,4]))# [4, 5, 5, 6]# or using oslash, it can alternatively be written asList([1,2]).lift_a2(mult,List([3]))List([1,2]).lift_a2(lambdaa:lambdab:a+b,List([3,4]))
Lifting a one-argument function and applying it does the same thing asmap
.
increment=lambdax:x+1lift(increment)(List([2]))# [3]List([2]).map(increment)# [3]
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:
greet=lambda:'Hello World!'
Any invocation ofgreet()
can be replaced withHello World!
hence greet isreferentially transparent.
When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.
An anonymous function that can be treated like a value.
deff(a):returna+1lambdaa:a+1
Lambdas are often passed as arguments to Higher-Order functions.
List([1,2]).map(lambdax:x+1)# [2, 3]
You can assign a lambda to a variable.
add1=lambdaa:a+1
A branch of mathematics that uses functions to create auniversal model of computation.
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.
importrandomdefrand():whileTrue:yieldrandom.randint(1,101)
randIter=rand()next(randIter)# Each execution gives a random value, expression is evaluated on need.
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# 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# 1
It's also required that the grouping of operations will not affect the result (associativity):
1+ (2+3)== (1+2)+3# true
List concatenation also forms a monoid:
[1,2]+ [3,4]# [1, 2, 3, 4]
The identity value is empty array[]
[1,2]+ []# [1, 2]
If identity and compose functions are provided, functions themselves form a monoid:
identity=lambdaa:acompose=lambdaf,g:lambdax:f(g(x))
foo
is any function that takes one argument.
compose(foo, identity) ≍ compose(identity, foo) ≍ foo
A monad is an object withof
andchain
functions.chain
is likemap
except it un-nests the resulting nested object.
# pymonad Monad library https://bitbucket.org/jason_delaat/pymonadfrompymonad.Listimport*fromfunctoolsimportreduce#implementationclassArray(list):defof(*args):returnArray([aforainargs])defchain(self,f):returnreduce(lambdaacc,it:acc+f(it),self[:], [])defmap(self,f):return [f(x)forxinself[:]]# UsageArray.of('cat,dog','fish,bird').chain(lambdaa:a.split(','))# ['cat', 'dog', 'fish', 'bird']# Contrast to mapArray.of('cat,dog','fish,bird').map(lambdaa:a.split(','))# [['cat', 'dog'], ['fish', 'bird']]
of
is also known asreturn
in other functional languages.chain
is also known asflatmap
andbind
in other languages.
An object that hasextract
andextend
functions.
classCoIdentity:def__init__(self,v):self.val=vdefextract(self):returnself.valdefextend(f):returnCoIdentity(f(self))
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(lambdaco:co.extract()+1)# CoIdentity(2)
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.
fromfunctoolsimportreduce# ImplementationclassArray(list):defof(*args):returnArray([aforainargs])defchain(self,f):returnreduce(lambdaacc,it:acc+f(it),self[:], [])defmap(self,f):return [f(x)forxinself[:]]defap(self,xs):returnreduce(lambdaacc,f:acc+ (xs.map(f)),self[:], [])# Example usageArray([lambdaa:a+1]).ap(Array([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 combinearg1= [1,3]arg2= [4,5]# combining function - must be curried for this to workadd=lambdax:lambday:x+ypartially_applied_adds= [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:
partially_applied_adds.ap(arg2)# [5, 6, 7, 8]
A transformation function.
A function where the input type is the same as the output.
# uppercase :: String -> Stringuppercase=lambdas:s.upper()# decrement :: Number -> Numberdecrement=lambdax:x-1
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.fromcollectionsimportnamedtupleCoords=namedtuple('Coords','x y')pair_to_coords=lambdapair:Coords(pair[0],pair[1])coords_to_pair=lambdacoords: [coords.x,coords.y]coords_to_pair(pair_to_coords([1,2]))# [1, 2]pair_to_coords(coords_to_pair(Coords(1,2)))# Coords(x=1, y=2)
A homomorphism is just a structure preserving map. In fact, a functor is just a homomorphism between categories as it preserves the original category's structure under the mapping.
frompymonadimport*f*A.unit(x)==A.unit(f(x))(lambdax:x.upper())* (Either.unit("oreos"))==Either.unit("oreos".upper())
Areduce_right
function that applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
fromfunctoolsimportreduceclassArray(list):defreduce_right(self,f,init):returnreduce(f,self[::-1],init)sum=lambdaxs:xs.reduce_right(lambdaacc,x:acc+x,0)sum(Array([1,2,3,4,5]))# 15
Anunfold
function. Anunfold
is the opposite offold
(reduce
). It generates a list from a single value.
defunfold(f,seed):defgo(f,seed,acc):res=f(seed)returngo(f,res[1],acc+ [res[0]])ifreselseaccreturngo(f,seed, [])
count_down=lambdan:unfold(lambdan:Noneifn<=0else (n,n-1),n)count_down(5)# [5, 4, 3, 2, 1]
The combination of anamorphism and catamorphism.
A function just likereduce_right
. 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.
defpara(reducer,accumulator,elements):ifnotlen(elements):returnaccumulatorhead=elements[0]tail=elements[1:]returnreducer(head,tail,para(reducer,accumulator,tail))suffixes=lambdalst:para(lambdax,xs,suffxs: [xs,*suffxs], [],lst)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.
it's the opposite of paramorphism, just as anamorphism is the opposite of catamorphism. Whereas with paramorphism, you combine with access to the accumulator and what has been accumulated, apomorphism lets youunfold
with the potential to return early.
An object that has anequals
function which can be used to compare other objects of the same type.
Make array a setoid:
classArray(list):defequals(self,other):iflen(self)!=len(other):returnFalseelse:returnreduce(lambdaident,pair:identand (pair[0]==pair[1]),zip(self[:],other[:]),True)Array([1,2]).equals(Array([1,2]))# trueArray([1,2]).equals(Array([0]))# false
An object that has aconcat
function that combines it with another object of the same type.
[1]+ [2]# [1, 2]
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.
sum=lambdalst:reduce(lambdaacc,x:acc+x,lst,0)sum([1,2,3])# 6
A lens is a structure (often an object or function) that pairs a getter and a non-mutating setter for some other datastructure.
fromlensesimportlens# Using [python-lenses](https://python-lenses.readthedocs.io/en/latest/tutorial/methods.html)name_lens=lens['name']# we create an unbound lens which accesses the value associate with the 'name' key of a dict
Having the pair of get and set for a given data structure enables a few key features.
person= {'name':'Gertrude Blanch'}# invoke the gettername_lens.get()(person)# 'Gertrude Blanch'# invoke the settername_lens.set('Shafi Goldwasser')(person)# {'name': 'Shafi Goldwasser'}# run a function on the value in the structurename_lens.modify(lambdax:x.upper())(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 arrayfirst_lens=lens[0]people= [{'name':'Gertrude Blanch'}, {'name':'Shafi Goldwasser'}]# Despite what you may assume, lenses compose left-to-right.(first_lens&name_lens).modify(lambdax:x.upper())(people)# [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]
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:
# function :: a -> b -> c# add :: int -> int -> int# alternatively could be float -> float -> floatadd=lambday:lambdax:x+y# increment :: int -> intincrement=lambdax:x+1
If a function accepts another function as an argument it is wrapped in parentheses.
# call :: (a -> b) -> a -> bcall=lambdaf:lambdax: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]map(f,lst)
Further reading
- Ramda's type signatures
- Mostly Adequate Guide
- What is Hindley-Milner? on Stack Overflow
A composite type made from putting other types together. Two common classes of algebraic types aresum andproduct.
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 (neither does python) but we can useSet
s to pretend:
# imagine that rather than sets here we have types that can only have these valuesbools=set([True,False])half_true=set(['half-true'])# The weakLogic type contains the sum of the values from bools and halfTrueweak_logic_values=bools.union(half_true)
Sum types are sometimes called union types, discriminated unions, or tagged unions.
Thesumtypes library in Python helps with defining and using union types.
Aproduct type combines types together in a way you're probably more familiar with:
fromcollectionsimportnamedtuplePoint=namedtuple('Point','x y')# point :: (Number, Number) -> {x: Number, y: Number}point=lambdapair:Point(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.
See alsoSet theory.
Option is asum type with two cases often calledSome
andNone
.
Option is useful for composing functions that might not return a value.
# Naive definitionclass_Some:def__init__(self,v):self.val=vdefmap(self,f):return_Some(f(self.val))defchain(self,f):returnf(self.val)# None is a keyword in pythonclass_None:defmap(self,f):returnselfdefchain(self,f):returnself# maybe_prop :: String -> (String => a) -> Option amaybe_prop=lambdakey,obj:_None()ifkeynotinobjelseSome(obj[key])
Usechain
to sequence functions that returnOption
s
# get_item :: Cart -> Option CartItemget_item=lambdacart:maybe_prop('item',cart)# get_price :: Cart -> Option Floatget_price=lambdaitem:maybe_prop('price',item)# get_nested_price :: Cart -> Option aget_nested_price=lambdacart:get_item(cart).chain(get_price)get_nested_price({})# _None()get_nested_price({"item": {"foo":1}})# _None()get_nested_price({"item": {"price":9.99}})# _Some(9.99)
Option
is also known asMaybe
.Some
is sometimes calledJust
.None
is sometimes calledNothing
.
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-independant, 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 -> Numbertimes2=lambdan:n*2map(times2, [1,2,3]# [2, 4, 6]
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:
fromfunctoolsimportpartial# example 1: sum of the list# sum :: [int] -> intsum=partial(reduce,lambdaa,b:a+b,arr)sum([1,2,3])# 6sum([])# TypeError: reduce() of empty sequence with no initial value# example 2: get the first item in list# first :: [a] -> afirst=lambdaa:a[0]first([42])# 42first([])# IndexError# or even worse:first([[42]])[0]# 42first([])[0]# Uncaught TypeError: an IndexError is throw instead# example 3: repeat function N times# times :: int -> (int -> int) -> inttimes=lambdan:lambdafn:nand (fn(n),times(n-1)(fn))times(3)(print)# 3# 2# 1# out: (None, (None, (None, 0)))times(-1)(print)# RecursionError: maximum recursion depth exceeded while calling a Python object
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:
# re-order function arguments for easier partial function application_reduce=lambdafn,init,seq:reduce(fn,seq,init)# example 1: sum of the list# we can provide default value so it will always return result# sum :: [int] -> intsum=partial(_reduce,lambdaa,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 Afirst=lambdaa:_Some(a[0])iflen(a)else_None()first([42]).map(print)# 42first([]).map(print)# print won't execute at all# our previous worst casefirst([[42]]).map(lambdaa:print(a[0]))# 42first([]).map(lambdaa:print(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 :: int -> (int -> int) -> inttimes=lambdan:lambdafn:n>0and (fn(n),times(n-1)(fn))times(3)(print)# 3# 2# 1times(-1)(print)# 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 as well as to reason about.
A comprehensive curated list of functional programming libraries for Python can be foundhere
P.S: This repo is successful due to the wonderfulcontributions!
About
Jargon from the functional programming world in simple terms!
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.