Answer the question
In order to leave comments, you need to log in
How to implement a variadic pure function without type classes?
The essence of the problem is as follows. I want to create a variadic function for creating a list/array: list(1)(2)(3)(4)(5)() === [1, 2, 3, 4, 5]
But for simplicity of reasoning, let's take a variadic addition function (just not to think about the atomic operation of constructing a list from head and tail for now): sum(1)(2)(3)(4)(5)() === 1 + 2 + 3 + 4 + 5 === 15
Actually, I found a Haskell solution ( stackoverflow.com/questions /3467279/how-to-create-... ):
class SumRes r where
sumOf :: Integer -> r
instance SumRes Integer where
sumOf = id
instance (Integral a, SumRes r) => SumRes (a -> r) where
sumOf x = sumOf . (x +) . toInteger
sumOf 1 4 7 10 2 5 8 22 == 59
Answer the question
In order to leave comments, you need to log in
While describing the problem, he understood how to solve it. ))
function add(x) {
return function(y) {
return x + y;
};
}
function sum(a) {
return function(b) {
if (b) {
return sum(add(a)(b));
} else {
return a;
}
};
}
sum(1)(2)(3)(4)(5)() === 15
function cons(x) {
return function(y) {
return [x, y];
};
}
function list(a) {
return function(b) {
if (b) {
return list(cons(a)(b));
} else {
return a;
}
};
}
list(1)(2)(3)(4)(5)() === ]
Are you sure you wanted to get just such an array?
Regarding the same amount, I will give you an interesting idea to play around with:
function sum(a) {
var sum = a;
function _sum(b) {
if (b === undefined) return sum;
sum += b;
return _sum;
}
_sum.toString = function() {
return sum;
};
return _sum;
}
sum(1)(2)(3) + sum(2)(2) + sum(sum(1)(2)(3))(4)(5); // 25
sum(1)(2)(0)(3)()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question