SlideShare a Scribd company logo
HIGHER-ORDER FUNCTIONS- WHAT ARE THEY?
They are functions ( what a surprise !) that do one or both of the following:
 Take other functions as parameters
 return a function
For this discussion the term function will refer to “pure functions”
i.e., functions that return the same value if they are called with the same
arguments.
TYPES OF FUNCTIONS
function Add(x,y) {
return x+y
}
function Add (x,y) {
console.log (x+y)
return x+y
}
function newadder(x){
return function (y){
return x+y
}
}
function fn ( another function) {
return anotherfunction()
}
function fnfn (another fn){
return function (x){
return anotherfn()+x
}
}

<- a pure function

<- a function with side effects
<- a function that returns
another function

<- function that takes another
function and returns a value.
<-a function that takes another
function and returns yet another
function!!
CURRYING
Nothing to do with Indian cuisine. It is a reference to the mathematician Haskell
Curry, who re-discovered Moses Schonfinkel‟s work on these types of
functions.
A technique of converting a function that takes multiple arguments to a chain of
functions that take one argument each.
For example: f (a,b)-> a+b .=> curried_f(a)(b)
 curried_f is a higher order function that takes „a‟ as an argument and returns a
function ( let us called it g(b) ). The function g() is called with „b‟ as its argument.
 When curried_f() is called with a single argument „a‟ it returns a function g(b) where the
value of „a‟ is fixed . In this case curried_f(10) will return function g(b) that returns the
value 10+ „b‟. ( g(1) will be 11 , g(2) will be 12 etc.
CURRIED FUNCTIONS EXAMPLES

function Add(x,y) {
return x+y
}
function curry_add(a){
return function(b){
return a+b
}
}
Usage:
Add10=curry_add(10)
Add10(100) -> 110

<- normal add function;

<“curried” version
Returns a new function that
takes „b‟ as an argument and
returns the value of a+b

<- Add10 is a new function that
takes 10 as an argument and
returns a function that returns 10
+ whatever is passed to it.
add10(b)-> 10 +b
CURRIED FUNCTIONS EXAMPLES
function AddMul(x,y,z) {
return (x*y)+z
}
function curry_addMul(a){
return function(b){
return function(c) {
return (a*b)+c
}
}
}
}

<- normal arith function with three
arguments

Curried vesrion:addmul(a)(b)(c)
Equivalent to the one above

Usage:
myAddMul=curry_addMul(10)(20)
myAddMul(100) -> 300

<- Myaddmul is a new function that takes 10
and 20 as argument s and returns a function
that returns (10*20) + whatever is passed to
it.
Myaddmul(b)-> (10*20 )+b

myOtherAddMul=curry_addMul(10)
myOtherAddMul(30)(40)-> (10*30)+40

<- myOtherAddMul is a function like this‟
function (y)
{ return function(z)
{ return (10*y)+ z }}
CURRY FUNCTIONS- A PROGRAMMER’S DEFINITION
In general, one can create N functions out of a function that takes N arguments.
Each of these functions is a “partial” function in which the 1st few arguments are
bound to their values at the time of creation of the “curried” function.
Note: There is a difference between “partial functions” and curry functions. But that is not
relevant from a practical programming perspective.
CREATING CURRIED FUNCTIONS
A function with n arguments f(x1,x2… xn) { <body> }
can be converted a curried version in the following
manner.
f (fn) -> {

return f (x1)
{
return f (x2)
.
..
return f(xn)
{
return fn(x1,x2… xn)
}
..
..
}
}
CREATING CURRIED FUNCTIONS IN JAVASCRIPT

There are two ways to create
curried equivalents of any
function in java script
 Using the new Function- creating a new function on the fly
 Using a closure
USING NEW FUNCTION() TO CREATE “CURRIED”
FUNCTIONS
curryf= function(nargs){
var fbody=""
var finalargs=""
for(var i=0;i<nargs;i++) {
var arg= "x" + i;
fbody+='return function('+arg+')'+ '{n'
finalargs+=arg
if(i<nargs-1)
finalargs+=','
}
fbody+="return anyfun("+finalargs+")n"
for ( i=0;i<nargs;i++){
fbody+="}n"
}
return new Function("anyfun",fbody)
}

<- creates a a function for a given number of
argumentsn , if nargs is 3 it will create and return a
the following function:
curryf(3)->
function (anyfun) {
return function (x0){
return function (x1){
return function(x2) {
return anyfun(x0,x1,x2)
}
}
}
Using the function:
Add= function (a,b) { return a+b}
curried_fn_2args=curryf(2)
curried_add= curried_fn_2args(Add)
curried_add(10)(20) -> 30
Add10= curried_add(10)
Add(100)= curried_add(100)
Add10(5) ->15
Add100(5) -> 105
Note: curriend_fn_2args can be used to create a
curried equivalent of ANY function with two
arguments.
PROS AND CONS OF USING THE NEW FUNCTION
Pros
 Creates functions that can be used in the “mathematical” syntax of curry
functions f(,a,b,c)-> f(a)(b)(c)
Cons
 Difficult to understand
 Imperative– automates the manual way of creating curry functions
 Creating functions using new Function is not advisable- slow, some of the
documentation says that functions created using new Function cannot have
closure- this particular example works in Chrome
A BETTER WAY TO CREATE CURRIED FUNCTION
Given the not-so-good attributes of the solution created using “new
Function”, the following section defines a better way of creating „curried”
functions
USING NEW FUNCTION() TO CREATE “CURRIED”
FUNCTIONS
var curry=function (fn) {
var ,
curry_args=
[].slice.call(arguments,1);
return function() {

return
fn.apply(this,curry_args.concat([].slice.call(
arguments)))
}
}

fn – function to be curried

Get partial or all arguments
passed to the curried function at
the time of „creation”. If args==[]
then curried function will expect
all the arrgs of fn().
<_ return a function that applies
the function fn will the all the
arguments– by concatenating
curry_args with the arguments
passed to the inner function
Usage: add(a,b) { return a+b}
Add10= curry(add,10)
Add10(20) -> 30
A PRACTICAL EXAMPLE OF USING CURRIED
FUNCTIONS
function converter(from, to, ratio,input) {
return [input,from,"equals
",(input*ratio),to].join(' ')
}
dlrToRupee= curry(converter, “$”,”Re”, 61)
euroToRupee=
curry(converter, “Euro(s)”, “$”, 1.35)
dlrTo Rupee(1000) ->“1000 $ equal 61000
re)
euroToDollar(100)->
“100 Euro(s ) equals 135 $”
milesToKm= curry
(converter, “Mile(s)”, „Kms”,
1.61)
mileToKm(100)->
“100 Mile(s) equals 161 Kms”

Converter(“$”, “Re”, 61, 100) will
return :
“100 $ equals 6100 Rs)

dlrToRuppee=> a new fn
function (input) {
return [input,”$”,"equals
",(input*ratio),”Re].join(' ')
milesToKm=> a new fn
function(input){
return [input,”Mile(s),"equals
",(input*ratio),”Kms”].join(' ')

As you can see many
functions can be created from
one converter function. This is
the primary use of currying.
ANOTHER EXAMPLE OF USING CURRIED FUNCTIONS
function getFile(callback, “path”, filename)
{
/* go your ajax stuff here*/
}

Self explanatory

getPdf= curry( getFile, pdfCallBack,
“/index/files/docs/pdf”)

getJpeg= curry(getFile,jpgCallback,
„/index/filex/images/jpg”
getPdf(“curryfunctions”)
getJpeg(“captainkirk”)

(a) Cleaner code– no passing
around long paths and
callback functions at every
place where you want to get
a PDF or an image.
(b) If the path or callback
change , you need to change
it only at one place
That‟s it! Currying is as simple as that.
Enjoy!

More Related Content

What's hot

Introduction to GCP (Google Cloud Platform)
Introduction to GCP (Google Cloud Platform)Introduction to GCP (Google Cloud Platform)
Introduction to GCP (Google Cloud Platform)
Pulkit Gupta
 
Productionzing ML Model Using MLflow Model Serving
Productionzing ML Model Using MLflow Model ServingProductionzing ML Model Using MLflow Model Serving
Productionzing ML Model Using MLflow Model Serving
Databricks
 
Databricks + Snowflake: Catalyzing Data and AI Initiatives
Databricks + Snowflake: Catalyzing Data and AI InitiativesDatabricks + Snowflake: Catalyzing Data and AI Initiatives
Databricks + Snowflake: Catalyzing Data and AI Initiatives
Databricks
 
Google Cloud Fundamentals by CloudZone
Google Cloud Fundamentals by CloudZoneGoogle Cloud Fundamentals by CloudZone
Google Cloud Fundamentals by CloudZone
Idan Tohami
 
Introduction to Amazon DynamoDB
Introduction to Amazon DynamoDBIntroduction to Amazon DynamoDB
Introduction to Amazon DynamoDB
Amazon Web Services
 
A Cloud Journey - Move to the Oracle Cloud
A Cloud Journey - Move to the Oracle CloudA Cloud Journey - Move to the Oracle Cloud
A Cloud Journey - Move to the Oracle Cloud
Markus Michalewicz
 
Google Cloud Platform
Google Cloud PlatformGoogle Cloud Platform
Google Cloud Platform
GeneXus
 
Understanding cloud with Google Cloud Platform
Understanding cloud with Google Cloud PlatformUnderstanding cloud with Google Cloud Platform
Understanding cloud with Google Cloud Platform
Dr. Ketan Parmar
 
Elastic stack Presentation
Elastic stack PresentationElastic stack Presentation
Elastic stack Presentation
Amr Alaa Yassen
 
Aws introduction
Aws introductionAws introduction
Aws introduction
MouryaKumar Reddy Rajala
 
Introducing Databricks Delta
Introducing Databricks DeltaIntroducing Databricks Delta
Introducing Databricks Delta
Databricks
 
Terraform
TerraformTerraform
Using AIOps to reduce incidents volume
Using AIOps to reduce incidents volumeUsing AIOps to reduce incidents volume
Using AIOps to reduce incidents volume
Amazon Web Services
 
Introduction to Google Cloud Platform
Introduction to Google Cloud PlatformIntroduction to Google Cloud Platform
Introduction to Google Cloud Platform
Sujai Prakasam
 
Apache Arrow Flight Overview
Apache Arrow Flight OverviewApache Arrow Flight Overview
Apache Arrow Flight Overview
Jacques Nadeau
 
Dynatrace Cloud-Native Workshop Slides
Dynatrace Cloud-Native Workshop SlidesDynatrace Cloud-Native Workshop Slides
Dynatrace Cloud-Native Workshop Slides
VMware Tanzu
 
Kappa vs Lambda Architectures and Technology Comparison
Kappa vs Lambda Architectures and Technology ComparisonKappa vs Lambda Architectures and Technology Comparison
Kappa vs Lambda Architectures and Technology Comparison
Kai Wähner
 
Microservices for Application Modernisation
Microservices for Application ModernisationMicroservices for Application Modernisation
Microservices for Application Modernisation
Ajay Kumar Uppal
 
Microsoft Azure Technical Overview
Microsoft Azure Technical OverviewMicrosoft Azure Technical Overview
Microsoft Azure Technical Overview
gjuljo
 
Azure migration
Azure migrationAzure migration
Azure migration
Arnon Rotem-Gal-Oz
 

What's hot (20)

Introduction to GCP (Google Cloud Platform)
Introduction to GCP (Google Cloud Platform)Introduction to GCP (Google Cloud Platform)
Introduction to GCP (Google Cloud Platform)
 
Productionzing ML Model Using MLflow Model Serving
Productionzing ML Model Using MLflow Model ServingProductionzing ML Model Using MLflow Model Serving
Productionzing ML Model Using MLflow Model Serving
 
Databricks + Snowflake: Catalyzing Data and AI Initiatives
Databricks + Snowflake: Catalyzing Data and AI InitiativesDatabricks + Snowflake: Catalyzing Data and AI Initiatives
Databricks + Snowflake: Catalyzing Data and AI Initiatives
 
Google Cloud Fundamentals by CloudZone
Google Cloud Fundamentals by CloudZoneGoogle Cloud Fundamentals by CloudZone
Google Cloud Fundamentals by CloudZone
 
Introduction to Amazon DynamoDB
Introduction to Amazon DynamoDBIntroduction to Amazon DynamoDB
Introduction to Amazon DynamoDB
 
A Cloud Journey - Move to the Oracle Cloud
A Cloud Journey - Move to the Oracle CloudA Cloud Journey - Move to the Oracle Cloud
A Cloud Journey - Move to the Oracle Cloud
 
Google Cloud Platform
Google Cloud PlatformGoogle Cloud Platform
Google Cloud Platform
 
Understanding cloud with Google Cloud Platform
Understanding cloud with Google Cloud PlatformUnderstanding cloud with Google Cloud Platform
Understanding cloud with Google Cloud Platform
 
Elastic stack Presentation
Elastic stack PresentationElastic stack Presentation
Elastic stack Presentation
 
Aws introduction
Aws introductionAws introduction
Aws introduction
 
Introducing Databricks Delta
Introducing Databricks DeltaIntroducing Databricks Delta
Introducing Databricks Delta
 
Terraform
TerraformTerraform
Terraform
 
Using AIOps to reduce incidents volume
Using AIOps to reduce incidents volumeUsing AIOps to reduce incidents volume
Using AIOps to reduce incidents volume
 
Introduction to Google Cloud Platform
Introduction to Google Cloud PlatformIntroduction to Google Cloud Platform
Introduction to Google Cloud Platform
 
Apache Arrow Flight Overview
Apache Arrow Flight OverviewApache Arrow Flight Overview
Apache Arrow Flight Overview
 
Dynatrace Cloud-Native Workshop Slides
Dynatrace Cloud-Native Workshop SlidesDynatrace Cloud-Native Workshop Slides
Dynatrace Cloud-Native Workshop Slides
 
Kappa vs Lambda Architectures and Technology Comparison
Kappa vs Lambda Architectures and Technology ComparisonKappa vs Lambda Architectures and Technology Comparison
Kappa vs Lambda Architectures and Technology Comparison
 
Microservices for Application Modernisation
Microservices for Application ModernisationMicroservices for Application Modernisation
Microservices for Application Modernisation
 
Microsoft Azure Technical Overview
Microsoft Azure Technical OverviewMicrosoft Azure Technical Overview
Microsoft Azure Technical Overview
 
Azure migration
Azure migrationAzure migration
Azure migration
 

Similar to Curry functions in Javascript

Function composition in Javascript
Function composition in JavascriptFunction composition in Javascript
Function composition in Javascript
Anand Kumar
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
David Atchley
 
Functional Javascript, CVjs
Functional Javascript, CVjsFunctional Javascript, CVjs
Functional Javascript, CVjs
kaw2
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
Maxim Zaks
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
Calvin Cheng
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
Muhammad Fayyaz
 
Python : Functions
Python : FunctionsPython : Functions
Monadologie
MonadologieMonadologie
Monadologie
league
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
Dhaval Dalal
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
Maneesh Chaturvedi
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
romanandreg
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
Nitish Phanse
 
JavaScript ∩ WebAssembly
JavaScript ∩ WebAssemblyJavaScript ∩ WebAssembly
JavaScript ∩ WebAssembly
Tadeu Zagallo
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
Jongsoo Lee
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
진성 오
 

Similar to Curry functions in Javascript (20)

Function composition in Javascript
Function composition in JavascriptFunction composition in Javascript
Function composition in Javascript
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Composition birds-and-recursion
Composition birds-and-recursionComposition birds-and-recursion
Composition birds-and-recursion
 
Functional Javascript, CVjs
Functional Javascript, CVjsFunctional Javascript, CVjs
Functional Javascript, CVjs
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Monadologie
MonadologieMonadologie
Monadologie
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Functional programming 101
Functional programming 101Functional programming 101
Functional programming 101
 
Why Haskell Matters
Why Haskell MattersWhy Haskell Matters
Why Haskell Matters
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Higher Order Components and Render Props
Higher Order Components and Render PropsHigher Order Components and Render Props
Higher Order Components and Render Props
 
JavaScript ∩ WebAssembly
JavaScript ∩ WebAssemblyJavaScript ∩ WebAssembly
JavaScript ∩ WebAssembly
 
Humble introduction to category theory in haskell
Humble introduction to category theory in haskellHumble introduction to category theory in haskell
Humble introduction to category theory in haskell
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 

Recently uploaded

A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 

Recently uploaded (20)

A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 

Curry functions in Javascript

  • 1.
  • 2. HIGHER-ORDER FUNCTIONS- WHAT ARE THEY? They are functions ( what a surprise !) that do one or both of the following:  Take other functions as parameters  return a function For this discussion the term function will refer to “pure functions” i.e., functions that return the same value if they are called with the same arguments.
  • 3. TYPES OF FUNCTIONS function Add(x,y) { return x+y } function Add (x,y) { console.log (x+y) return x+y } function newadder(x){ return function (y){ return x+y } } function fn ( another function) { return anotherfunction() } function fnfn (another fn){ return function (x){ return anotherfn()+x } } <- a pure function <- a function with side effects <- a function that returns another function <- function that takes another function and returns a value. <-a function that takes another function and returns yet another function!!
  • 4. CURRYING Nothing to do with Indian cuisine. It is a reference to the mathematician Haskell Curry, who re-discovered Moses Schonfinkel‟s work on these types of functions. A technique of converting a function that takes multiple arguments to a chain of functions that take one argument each. For example: f (a,b)-> a+b .=> curried_f(a)(b)  curried_f is a higher order function that takes „a‟ as an argument and returns a function ( let us called it g(b) ). The function g() is called with „b‟ as its argument.  When curried_f() is called with a single argument „a‟ it returns a function g(b) where the value of „a‟ is fixed . In this case curried_f(10) will return function g(b) that returns the value 10+ „b‟. ( g(1) will be 11 , g(2) will be 12 etc.
  • 5. CURRIED FUNCTIONS EXAMPLES function Add(x,y) { return x+y } function curry_add(a){ return function(b){ return a+b } } Usage: Add10=curry_add(10) Add10(100) -> 110 <- normal add function; <“curried” version Returns a new function that takes „b‟ as an argument and returns the value of a+b <- Add10 is a new function that takes 10 as an argument and returns a function that returns 10 + whatever is passed to it. add10(b)-> 10 +b
  • 6. CURRIED FUNCTIONS EXAMPLES function AddMul(x,y,z) { return (x*y)+z } function curry_addMul(a){ return function(b){ return function(c) { return (a*b)+c } } } } <- normal arith function with three arguments Curried vesrion:addmul(a)(b)(c) Equivalent to the one above Usage: myAddMul=curry_addMul(10)(20) myAddMul(100) -> 300 <- Myaddmul is a new function that takes 10 and 20 as argument s and returns a function that returns (10*20) + whatever is passed to it. Myaddmul(b)-> (10*20 )+b myOtherAddMul=curry_addMul(10) myOtherAddMul(30)(40)-> (10*30)+40 <- myOtherAddMul is a function like this‟ function (y) { return function(z) { return (10*y)+ z }}
  • 7. CURRY FUNCTIONS- A PROGRAMMER’S DEFINITION In general, one can create N functions out of a function that takes N arguments. Each of these functions is a “partial” function in which the 1st few arguments are bound to their values at the time of creation of the “curried” function. Note: There is a difference between “partial functions” and curry functions. But that is not relevant from a practical programming perspective.
  • 8. CREATING CURRIED FUNCTIONS A function with n arguments f(x1,x2… xn) { <body> } can be converted a curried version in the following manner. f (fn) -> { return f (x1) { return f (x2) . .. return f(xn) { return fn(x1,x2… xn) } .. .. } }
  • 9. CREATING CURRIED FUNCTIONS IN JAVASCRIPT There are two ways to create curried equivalents of any function in java script  Using the new Function- creating a new function on the fly  Using a closure
  • 10. USING NEW FUNCTION() TO CREATE “CURRIED” FUNCTIONS curryf= function(nargs){ var fbody="" var finalargs="" for(var i=0;i<nargs;i++) { var arg= "x" + i; fbody+='return function('+arg+')'+ '{n' finalargs+=arg if(i<nargs-1) finalargs+=',' } fbody+="return anyfun("+finalargs+")n" for ( i=0;i<nargs;i++){ fbody+="}n" } return new Function("anyfun",fbody) } <- creates a a function for a given number of argumentsn , if nargs is 3 it will create and return a the following function: curryf(3)-> function (anyfun) { return function (x0){ return function (x1){ return function(x2) { return anyfun(x0,x1,x2) } } } Using the function: Add= function (a,b) { return a+b} curried_fn_2args=curryf(2) curried_add= curried_fn_2args(Add) curried_add(10)(20) -> 30 Add10= curried_add(10) Add(100)= curried_add(100) Add10(5) ->15 Add100(5) -> 105 Note: curriend_fn_2args can be used to create a curried equivalent of ANY function with two arguments.
  • 11. PROS AND CONS OF USING THE NEW FUNCTION Pros  Creates functions that can be used in the “mathematical” syntax of curry functions f(,a,b,c)-> f(a)(b)(c) Cons  Difficult to understand  Imperative– automates the manual way of creating curry functions  Creating functions using new Function is not advisable- slow, some of the documentation says that functions created using new Function cannot have closure- this particular example works in Chrome
  • 12. A BETTER WAY TO CREATE CURRIED FUNCTION Given the not-so-good attributes of the solution created using “new Function”, the following section defines a better way of creating „curried” functions
  • 13. USING NEW FUNCTION() TO CREATE “CURRIED” FUNCTIONS var curry=function (fn) { var , curry_args= [].slice.call(arguments,1); return function() { return fn.apply(this,curry_args.concat([].slice.call( arguments))) } } fn – function to be curried Get partial or all arguments passed to the curried function at the time of „creation”. If args==[] then curried function will expect all the arrgs of fn(). <_ return a function that applies the function fn will the all the arguments– by concatenating curry_args with the arguments passed to the inner function Usage: add(a,b) { return a+b} Add10= curry(add,10) Add10(20) -> 30
  • 14. A PRACTICAL EXAMPLE OF USING CURRIED FUNCTIONS function converter(from, to, ratio,input) { return [input,from,"equals ",(input*ratio),to].join(' ') } dlrToRupee= curry(converter, “$”,”Re”, 61) euroToRupee= curry(converter, “Euro(s)”, “$”, 1.35) dlrTo Rupee(1000) ->“1000 $ equal 61000 re) euroToDollar(100)-> “100 Euro(s ) equals 135 $” milesToKm= curry (converter, “Mile(s)”, „Kms”, 1.61) mileToKm(100)-> “100 Mile(s) equals 161 Kms” Converter(“$”, “Re”, 61, 100) will return : “100 $ equals 6100 Rs) dlrToRuppee=> a new fn function (input) { return [input,”$”,"equals ",(input*ratio),”Re].join(' ') milesToKm=> a new fn function(input){ return [input,”Mile(s),"equals ",(input*ratio),”Kms”].join(' ') As you can see many functions can be created from one converter function. This is the primary use of currying.
  • 15. ANOTHER EXAMPLE OF USING CURRIED FUNCTIONS function getFile(callback, “path”, filename) { /* go your ajax stuff here*/ } Self explanatory getPdf= curry( getFile, pdfCallBack, “/index/files/docs/pdf”) getJpeg= curry(getFile,jpgCallback, „/index/filex/images/jpg” getPdf(“curryfunctions”) getJpeg(“captainkirk”) (a) Cleaner code– no passing around long paths and callback functions at every place where you want to get a PDF or an image. (b) If the path or callback change , you need to change it only at one place
  • 16. That‟s it! Currying is as simple as that. Enjoy!