Currying in Scala like JavaScript - javascript

Im new to functional programming in Scala and i'd like to know how to achieve the concept of currying in Scala. Below i have given an example of currying in JavaScript and I'd like to know the Scala equivalent of the same code.
var add = function(x){
return function(y){
return x + y;
};
};
console.log(add(1)(2));
var increment = add(1);
var addTen = add(10);
increment(2); //3
addTen(2); //12
Any Help would be appreciated :)

Let's first rewrite your example in more modern ECMAScript:
const add = x => y => x + y;
The Scala equivalent is very similar, it looks almost like this, the only difference is the val instead of const (although we could actually use var in both cases, and make the code truly identical):
// almost correct, but doesn't compile
val add = x => y => x + y
Except that doesn't work because Scala doesn't know what the types are, so we have to help just a little bit by either declaring the types of x and y, so Scala can properly infer the type of add or declare the type of add, so Scala can properly infer the types of the functions:
val add = (x: Int) => (y: Int) => x + y
// or
val add: Int => Int => Int = x => y => x + y
Scala also allows us to write them with a proper fat arrow if we want to:
val add = (x: Int) ⇒ (y: Int) ⇒ x + y
// or
val add: Int ⇒ Int ⇒ Int = x ⇒ y ⇒ x + y
So, as you can see, apart from the type declarations, the code is actually identical.
println(add(1)(2)) // 3
val increment = add(1)
val addTen = add(10)
increment(2) //=> 3
addTen(2) //=> 12
There is, however, another kind of currying in Scala, that is actually built into the language. In Scala, methods (which are different from functions) can have zero or more parameter lists, unlike most other languages (including ECMAScript) where there is always exactly one (potentially empty) parameter list. Methods that are defined with multiple parameter lists are called "curried" methods:
// this is a *method*, not a *function*, and thus different from the OP's example!
def addMeth(x: Int)(y: Int) = x + y
In Scala, we can convert a method into a function using η-expansion; this is written by placing an underscore after the name of the method:
// this converts the method `addMeth` into an anonymous function
// and assigns it to the variable `addFunc`
val addFunc = addMeth _
Now we can do the same things we did above using our curried addFunc function:
println(addFunc(1)(2)) // 3
val increment = addFunc(1)
val addTen = addFunc(10)
increment(2) //=> 3
addTen(2) //=> 12
But we can also use our addMeth method directly:
println(addMeth(1)(2)) // 3
val increment = addMeth(1) _
val addTen = addMeth(10) _
increment(2) //=> 3
addTen(2) //=> 12
So, unlike ECMAScript, Scala actually has a language built-in concept of currying, but
not for functions, only for methods and
not based on individual parameters but on parameter lists

Here it is:
def add(x:Int)(y:Int) = x+y
def increment = add(1) _
def addTen = add(10) _
val three = add(1)(2)
val four = increment(3)

Related

How to convert a .reduce function of Javascript to Python?

I am reading a javascript source and I need to convert it to Python.
Here is the code, since I am just a beginner, I dont get .reduce() function at all
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
Here is what I have tried so far
def bin2dec(num):
listNum = list(num)
listNum = map(int, listNum)
x = listNum[-1]
listNum.reverse()
for i in range (len(listNum)):
if listNum[i] == 1:
x = x + 2**listNum[i]
else:
x = x
return x
But it is not correct.
Normal Equivalence
Javascript parseInt(x, 2)
Python int(x, 2)
Using Same Method as Posted Code
from functools import reduce
import math
def bin2dec(s):
return reduce(lambda x, y_i: x + int(math.pow(2, y_i[0])) if y_i[1] == '1' else x,
enumerate(reversed(s)),
0)
Test
print(bin2dec('110')) # outut: 6
Explanation
reversed(s) to replace Javascript num.split('').reverse()
Python's reduce function from functools has signature reduce(function, iterable[, initializer])
Use Python lambda function in place of Javascript's function(x, y, i){... (1st argument)
Javascript reduce provide current value and current index y, i
Python only provides current value, so we use enumerate(..) on values array to convert to current index, current value pairs (2nd argument)
y_i are value tuples, with y_i[0] = index and y_i[1] the value
use 0 as initializer (last argument in reduce)
int to convert the value of math.pow from float to integer
Python if else expression in place of Javascript's ? ternary operator
Simpler Python Code than Using Reduce
def bin2dec(s):
return sum((0, 2**i)[y == '1'] for i, y in enumerate(s[::-1]))
You can just use the built-in int function:
int("010010", 2)
>>> 18
That said I found a pretty interesting alternative approach using js2py.
You can feed it the whole js function as a string, allowing you to effectively use js inside python:
import js2py
bin2dec = js2py.eval_js("""
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
""")
bin2dec("010010")
>>> 18
Install with pip install js2py
You made a lot of mistakes with your attempt, the map function returns an iterator, not a list. Generally, just avoid map and filter and just use a list comprehension instead.
You also raised 2 to the power of the value (1 or 0) when it should have been the index.
Here's a working version of your example:
def bin2dec(num):
listNum = [int(n) for n in num]
total = 0
listNum.reverse()
for i, n in enumerate(listNum):
if n == 1:
total += 2 ** i
return total

Pattern matching in JS on a PureScript sum-of-products type

I have an algebraic sum-of-products type in PureScript:
data IO
= Menu (Word8 -> Effect IO)
| LongMessage (Array String) (Effect IO)
| ShortMessage String (Effect IO)
| End
initialize :: Effect IO
I'd like to call initialize from JavaScript, and then consume its result. If I run Main.initialize() from JavaScript, I get a JS Object that prints like the following to console:
LongMessage3 {value0: Array(15), value1: ƒ}
value0: (1) ['foo']
value1: ƒ __do()
[[Prototype]]: Object
What would the JavaScript code look like that recognizes this object as a value corresponding to the LongMessage constructor?
First, to answer questions like this, you can just look at the compiled JS code yourself. It's located in ./output/My.Module.Name/index.js. Just open it and take a look.
But for completeness, here's the answer:
The current version of PureScript (0.15.2 as of this writing) compiles ADTs to a set of JS objects with unique prototypes.
I'm going to use a smaller example, because yours is a bit too large to be legible. Let's say my ADT looks like this:
data X = Y Int | Z String Boolean
a = Y 42
b = Z "foo" false
This would yield roughly the following JS (I say "roughly" because it's a bit more elaborate, but the essence is the same):
function Y(value0) {
this.value0 = value0
}
function Z(value0, value1) {
this.value0 = value0
this.value1 = value1
}
var a = new Y(42)
var b = new Z("foo", false)
When constructed like this, values of the type can be tested for the particular constructor by checking the prototype via instanceof. So, for example, the following:
c = case a of
Y _ -> "It's a Y"
Z s _ -> "It's a Z with " <> s
would translate roughly to:
var c = (() => {
if (a instanceof Y) {
return "It's a Y"
}
if (a instanceof Z) {
return "It's a Z with " + a.value0
}
throw new Error("Invalid pattern match")
})()
A footnote: in your example the constructor seems to be named LogMessage3 instead of LogMessage. This tells me that you're probably executing a bundle. During bundling functions may get renamed to avoid naming conflicts - that's where the "3" comes from.

Are 'currying' and 'composition' the same concept in Javascript?

Recently I read about function composition in a Javascript book, and then on a website I saw someone reference it as currying.
Are they the same concept?
#Omarjmh's answer is good but the compose example is overwhelmingly complex for a learner, in my opinion
Are they the same concept?
No.
First, currying is translating a function that takes multiple arguments into a sequence of functions, each accepting one argument.
// not curried
const add = (x,y) => x + y;
add(2,3); // => 5
// curried
const add = x => y => x + y;
add(2)(3); // => 5
Notice the distinct way in which a curried function is applied, one argument at a time.
Second, function composition is the combination of two functions into one, that when applied, returns the result of the chained functions.
const compose = f => g => x => f(g(x));
compose (x => x * 4) (x => x + 3) (2);
// (2 + 3) * 4
// => 20
The two concepts are closely related as they play well with one another. Generic function composition works with unary functions (functions that take one argument) and curried functions also only accept one argument (per application).
// curried add function
const add = x => y => y + x;
// curried multiplication function
const mult = x => y => y * x;
// create a composition
// notice we only apply 2 of comp's 3 parameters
// notice we only apply 1 of mult's 2 parameters
// notice we only apply 1 of add's 2 parameters
let add10ThenMultiplyBy3 = compose (mult(3)) (add(10));
// apply the composition to 4
add10ThenMultiplyBy3(4); //=> 42
// apply the composition to 5
add10ThenMultiplyBy3(5); //=> 45
Composition and currying are used to create functions. Composition and currying differ in the way they create new functions (by applying args vs chaining).
Compose:
Compose should return a function that is the composition of a list of functions of arbitrary length. Each function is called on the return value of the function that follows. You can think of compose as moving right to left through its arguments.
Example:
var compose = function(funcs) {
funcs = Array.prototype.slice.call(arguments, 0);
return function(arg) {
return funcs.reduceRight(function (a, b) {
a = a === null ? a = b(arg) : a = b(a);
return a;
}, null);
};
};
var sayHi = function(name){ return 'hi: ' + name;};
var makeLouder = function(statement) { return statement.toUpperCase() + '!';};
var hello = compose(sayHi, makeLouder);
l(hello('Johhny')); //=> 'hi: JOHNNY!'
Currying:
Currying is a way of constructing functions that allows partial application of a function’s arguments.
Example:
var addOne = add(1);
var addTwo = add(2);
var addOneToFive = addOne(5);
var addTwoToFive = addTwo(5);
l(addOneToFive); //6
l(addTwoToFive); //7
JSBin with the above examples:
https://jsbin.com/jibuje/edit?js,console

How do I write an arrow function in ES6 recursively?

Arrow functions in ES6 do not have an arguments property and therefore arguments.callee will not work and would anyway not work in strict mode even if just an anonymous function was being used.
Arrow functions cannot be named, so the named functional expression trick can not be used.
So... How does one write a recursive arrow function? That is an arrow function that recursively calls itself based on certain conditions and so on of-course?
Writing a recursive function without naming it is a problem that is as old as computer science itself (even older, actually, since λ-calculus predates computer science), since in λ-calculus all functions are anonymous, and yet you still need recursion.
The solution is to use a fixpoint combinator, usually the Y combinator. This looks something like this:
(y =>
y(
givenFact =>
n =>
n < 2 ? 1 : n * givenFact(n-1)
)(5)
)(le =>
(f =>
f(f)
)(f =>
le(x => (f(f))(x))
)
);
This will compute the factorial of 5 recursively.
Note: the code is heavily based on this: The Y Combinator explained with JavaScript. All credit should go to the original author. I mostly just "harmonized" (is that what you call refactoring old code with new features from ES/Harmony?) it.
It looks like you can assign arrow functions to a variable and use it to call the function recursively.
var complex = (a, b) => {
if (a > b) {
return a;
} else {
complex(a, b);
}
};
Claus Reinke has given an answer to your question in a discussion on the esdiscuss.org website.
In ES6 you have to define what he calls a recursion combinator.
let rec = (f)=> (..args)=> f( (..args)=>rec(f)(..args), ..args )
If you want to call a recursive arrow function, you have to call the recursion combinator with the arrow function as parameter, the first parameter of the arrow function is a recursive function and the rest are the parameters. The name of the recursive function has no importance as it would not be used outside the recursive combinator. You can then call the anonymous arrow function. Here we compute the factorial of 6.
rec( (f,n) => (n>1 ? n*f(n-1) : n) )(6)
If you want to test it in Firefox you need to use the ES5 translation of the recursion combinator:
function rec(f){
return function(){
return f.apply(this,[
function(){
return rec(f).apply(this,arguments);
}
].concat(Array.prototype.slice.call(arguments))
);
}
}
TL;DR:
const rec = f => f((...xs) => rec(f)(...xs));
There are many answers here with variations on a proper Y -- but that's a bit redundant... The thing is that the usual way Y is explained is "what if there is no recursion", so Y itself cannot refer to itself. But since the goal here is a practical combinator, there's no reason to do that. There's this answer that defines rec using itself, but it's complicated and kind of ugly since it adds an argument instead of currying.
The simple recursively-defined Y is
const rec = f => f(rec(f));
but since JS isn't lazy, the above adds the necessary wrapping.
Use a variable to which you assign the function, e.g.
const fac = (n) => n>0 ? n*fac(n-1) : 1;
If you really need it anonymous, use the Y combinator, like this:
const Y = (f) => ((x)=>f((v)=>x(x)(v)))((x)=>f((v)=>x(x)(v)))
… Y((fac)=>(n)=> n>0 ? n*fac(n-1) : 1) …
(ugly, isn't it?)
A general purpose combinator for recursive function definitions of any number of arguments (without using the variable inside itself) would be:
const rec = (le => ((f => f(f))(f => (le((...x) => f(f)(...x))))));
This could be used for example to define factorial:
const factorial = rec( fact => (n => n < 2 ? 1 : n * fact(n - 1)) );
//factorial(5): 120
or string reverse:
const reverse = rec(
rev => (
(w, start) => typeof(start) === "string"
? (!w ? start : rev(w.substring(1), w[0] + start))
: rev(w, '')
)
);
//reverse("olleh"): "hello"
or in-order tree traversal:
const inorder = rec(go => ((node, visit) => !!(node && [go(node.left, visit), visit(node), go(node.right, visit)])));
//inorder({left:{value:3},value:4,right:{value:5}}, function(n) {console.log(n.value)})
// calls console.log(3)
// calls console.log(4)
// calls console.log(5)
// returns true
I found the provided solutions really complicated, and honestly couldn't understand any of them, so i thought out a simpler solution myself (I'm sure it's already known, but here goes my thinking process):
So you're making a factorial function
x => x < 2 ? x : x * (???)
the (???) is where the function is supposed to call itself, but since you can't name it, the obvious solution is to pass it as an argument to itself
f => x => x < 2 ? x : x * f(x-1)
This won't work though. because when we call f(x-1) we're calling this function itself, and we just defined it's arguments as 1) f: the function itself, again and 2) x the value. Well we do have the function itself, f remember? so just pass it first:
f => x => x < 2 ? x : x * f(f)(x-1)
^ the new bit
And that's it. We just made a function that takes itself as the first argument, producing the Factorial function! Just literally pass it to itself:
(f => x => x < 2 ? x : x * f(f)(x-1))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Instead of writing it twice, you can make another function that passes it's argument to itself:
y => y(y)
and pass your factorial making function to it:
(y => y(y))(f => x => x < 2 ? x : x * f(f)(x-1))(5)
>120
Boom. Here's a little formula:
(y => y(y))(f => x => endCondition(x) ? default(x) : operation(x)(f(f)(nextStep(x))))
For a basic function that adds numbers from 0 to x, endCondition is when you need to stop recurring, so x => x == 0. default is the last value you give once endCondition is met, so x => x. operation is simply the operation you're doing on every recursion, like multiplying in Factorial or adding in Fibonacci: x1 => x2 => x1 + x2. and lastly nextStep is the next value to pass to the function, which is usually the current value minus one: x => x - 1. Apply:
(y => y(y))(f => x => x == 0 ? x : x + f(f)(x - 1))(5)
>15
var rec = () => {rec()};
rec();
Would that be an option?
Since arguments.callee is a bad option due to deprecation/doesnt work in strict mode, and doing something like var func = () => {} is also bad, this a hack like described in this answer is probably your only option:
javascript: recursive anonymous function?
This is a version of this answer, https://stackoverflow.com/a/3903334/689223, with arrow functions.
You can use the U or the Y combinator. Y combinator being the simplest to use.
U combinator, with this you have to keep passing the function:
const U = f => f(f)
U(selfFn => arg => selfFn(selfFn)('to infinity and beyond'))
Y combinator, with this you don't have to keep passing the function:
const Y = gen => U(f => gen((...args) => f(f)(...args)))
Y(selfFn => arg => selfFn('to infinity and beyond'))
You can assign your function to a variable inside an iife
var countdown = f=>(f=a=>{
console.log(a)
if(a>0) f(--a)
})()
countdown(3)
//3
//2
//1
//0
i think the simplest solution is looking at the only thing that you don't have, which is a reference to the function itself. because if you have that then recusion is trivial.
amazingly that is possible through a higher order function.
let generateTheNeededValue = (f, ...args) => f(f, ...args);
this function as the name sugests, it will generate the reference that we'll need. now we only need to apply this to our function
(generateTheNeededValue)(ourFunction, ourFunctionArgs)
but the problem with using this thing is that our function definition needs to expect a very special first argument
let ourFunction = (me, ...ourArgs) => {...}
i like to call this special value as 'me'. and now everytime we need recursion we do like this
me(me, ...argsOnRecursion);
with all of that. we can now create a simple factorial function.
((f, ...args) => f(f, ...args))((me, x) => {
if(x < 2) {
return 1;
} else {
return x * me(me, x - 1);
}
}, 4)
-> 24
i also like to look at the one liner of this
((f, ...args) => f(f, ...args))((me, x) => (x < 2) ? 1 : (x * me(me, x - 1)), 4)
Here is the example of recursive function js es6.
let filterGroups = [
{name: 'Filter Group 1'}
];
const generateGroupName = (nextNumber) => {
let gN = `Filter Group ${nextNumber}`;
let exists = filterGroups.find((g) => g.name === gN);
return exists === undefined ? gN : generateGroupName(++nextNumber); // Important
};
let fg = generateGroupName(filterGroups.length);
filterGroups.push({name: fg});

Is it possible to define an infix function?

Is it possible to define my own infix function/operator in CoffeeScript (or in pure JavaScript)? e.g. I want to call
a foo b
or
a `foo` b
instead of
a.foo b
or, when foo is global function,
foo a, b
Is there any way to do this?
ES6 enables a very Haskell/Lambda calculus way of doing things.
Given a multiplication function:
const multiply = a => b => (a * b)
You can define a doubling function using partial application (you leave out one parameter):
const double = multiply (2)
And you can compose the double function with itself, creating a quadruple function:
const compose = (f, g) => x => f(g(x))
const quadruple = compose (double, double)
But indeed, what if you would prefer an infix notation? As Steve Ladavich noted, you do need to extend a prototype.
But I think it can be done a bit more elegant using array notation instead of dot notation.
Lets use the official symbol for function composition "∘":
Function.prototype['∘'] = function(f){
return x => this(f(x))
}
const multiply = a => b => (a * b)
const double = multiply (2)
const doublethreetimes = (double) ['∘'] (double) ['∘'] (double)
console.log(doublethreetimes(3));
Actually adding this as an answer: no, this is not possible.
It's not possible in vanilla JS.
It's not possible in CoffeeScript.
You can with sweet.js. See:
http://sweetjs.org/doc/main/sweet.html#infix-macros
http://sweetjs.org/doc/main/sweet.html#custom-operators
Sweet.js extends Javascript with macros.
It acts like a preprocessor.
This is definitely not infix notation but it's kinda close : /
let plus = function(a,b){return a+b};
let a = 3;
let b = 5;
let c = a._(plus).b // 8
I don't think anyone would actually want to use this "notation" since it's pretty ugly, but I think there are probably some tweaks that can be made to make it look different or nicer (possibly using this answer here to "call a function" without parentheses).
Infix function
// Add to prototype so that it's always there for you
Object.prototype._ = function(binaryOperator){
// The first operand is captured in the this keyword
let operand1 = this;
// Use a proxy to capture the second operand with "get"
// Note that the first operand and the applied function
// are stored in the get function's closure, since operand2
// is just a string, for eval(operand2) to be in scope,
// the value for operand2 must be defined globally
return new Proxy({},{
get: function(obj, operand2){
return binaryOperator(operand1, eval(operand2))
}
})
}
Also note that the second operand is passed as a string and evaluated with eval to get its value. Because of this, I think the code will break anytime the value of operand (aka "b") is not defined globally.
Javascript doesn't include an infix notation for functions or sections for partial application. But it ships with higher order functions, which allow us to do almost everything:
// applicator for infix notation
const $ = (x, f, y) => f(x) (y);
// for left section
const $_ = (x, f) => f(x);
// for right section
const _$ = (f, y) => x => f(x) (y);
// non-commutative operator function
const sub = x => y => x - y;
// application
console.log(
$(2, sub, 3), // -1
$_(2, sub) (3), // -1
_$(sub, 3) (2) // -1
);
As you can see I prefer visual names $, $_ and _$ to textual ones in this case. This is the best you can get - at least with pure Javascript/ES2015.
You can get close by function currying:
const $ = (a) => (f) => f(a);
const plus = (a) => (b) => (a+b);
const twoPlusThree = $ (2) (plus) (3);
But I still haven't figured out a neat way to compose this construction.

Categories

Resources