Name for this function invocation style - functional-programming

Functions can be written in a way to permit the "spreading" of invocations
console.assert(add(1,2,3,4) === 10, '1+2+3+4 should be 10');
console.assert(add(1,2)(3)(4)() === 10, '1+2+3+4 should be 10'); // "spread" invocation
What is the name for this pattern?

It is called currying.
Imagine that add is a function that receives 4 arguments:
function add(a,b,c,d);
If you pass exactly 4 arguments, it returns the sum of all of them.
If you pass 3, (e.g. a=1, b=2, c=3) it will return a function that receives one parameter and adds that to 1+2+3 (the values of a,b,c).
If you pass 2, it will return a function that receives two parameters and returns the sum of those with the intial 2 parameters that you passed.
An example, if you, like me, have from a imperative language background.
function add(a, b, c, d){
if(arguments.length < 1){
return add
} else if(arguments.length < 2){
return function(b, c, d) { return add(a,b,c,d) }
} else if(arguments.length < 3){
return function(c, d) { return add(a,b,c,d) }
} else if(arguments.length < 4){
return function(d) { return add(a,b,c,d) }
} else {
return a+b+c+d;
}
}

Related

Need help recursion explanation Leetcode

How does this code work? (leetcode 95 question) I don't understand how the 2 recursions work inside the for loop. Does the 2nd inner for loop end when the recursive function returns NULL? Or would it continue executing the 3rd inner for loop?
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if(n == 0) {
return {};
}
vector<TreeNode*> ans = generateT(1,n);
return ans;
}
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return {nullptr};
vector<TreeNode*> ans;
for(int i=l; i <= r; ++i) {
for(TreeNode*left: generateT(l, i-1)) {
for(TreeNode* right:generateT(i+1, r)) {
ans.push_back(new TreeNode(i));
ans.back()->left = left;
ans.back()->right = right;
}
}
}
return ans;
}
};
Problem statement:
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Does the 2nd inner for loop end when the recursive function returns NULL?
No. The recursive function is not returing NULL, it is returning vector of nullptr.
Or would it continue executing the 3rd inner for loop?
Of course, it will.
How does this code work? I don't understand how the 2 recursions work inside the loop.
I suppose the following snippet is the cause of confusion, so commented the case when nullptr provided by outer loop.
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return { nullptr };
vector<TreeNode*> ans;
for ( int i = l; i <= r; i++ ) {
// if l = 0, i = 0
for ( TreeNode* left :generateT(l, i-1) ) // if l = 0, i = -1, returns { nullptr } (vector of nullptr)
for (TreeNode* right :generateT(i+1, r)) { // now this snippet will execute
auto node = new TreeNode(i);
ans.push_back(node);
node->left = left; // the nullptr we have from the outer loop, will provide null value for this
node->right = right;
}
}
return ans;
}
Visually, for a combination of node where,
a
\
b
/ \
null c
/
null
the above pattern occurs the provided { nullptr } from outer loop will come in handy setting left node.

If else statement to check if any numbers are negative in R

This is probably very simple, but I am not sure why it's not working.
For input vector b, I want to write a function which begins by checking b for any negative values. If there are any, then the function stops. Otherwise, it continues. What the function is doesn't matter.
Something like this:
F <- function(b) {
if (any(b) < 0) {
warning("error")
} else {
# the function I want to put in
}
}
Edit:
The code that works is
F <- function(b) {
if (any(b < 0)) {
stop("error")
} else {
# the function I want to put in
}
}

Three function in R

IS <- function(N,K,sigma,t,r,S_0,a,b,tol){
funct_1 <- function(x){
return((S_0*(exp(-0.5*(sigma^2)*t+sigma*sqrt(t)*x))*(sigma*sqrt(t)-x))+
(exp(-r*t))*K*x)
}
bisection_method <- function(a, b, tol, f = funct_1){
if (f(a)*f(b) > 0){
print("No root found.")
} else
while ((b - a)/2.0 > tol){
midpt= (a + b)/2.0
if (f(midpt) == 0){
return(midpt)
} else if (f(a)*f(midpt) < 0){
b = midpt
} else
a = midpt
}
return(midpt)
}
}
The above function will produce nothing for you. My goal that to input the values of "N,K,sigma,t,r,S_0, a,b" and somehow return "midpt" for me. I have searched a lot but could not come up with anything that makes sense. I have many problems, assume that I input everything things, then how the function "funct_1" will output expression, this expression needs to be recalled to the next function "bisection_method} along with the value of a and b then finally obtain the "midpt" value. Any suggestions are really appreciated. Please let me know if there is anything not clear to you at all.
Your main function doesn't return anything. It just creates the auxiliary functions and then do nothing. That's why you're getting no output.
Try returning the bisection method with appropriate parameters in your main function instead. I also edited so you get NULL output when no root is found.
IS <- function(N,K,sigma,t,r,S_0,a,b,tol){
funct_1 <- function(x){
return((S_0*(exp(-0.5*(sigma^2)*t+sigma*sqrt(t)*x))*(sigma*sqrt(t)-x))+
(exp(-r*t))*K*x)
}
bisection_method <- function(a, b, tol, f = funct_1){
if (f(a)*f(b) > 0){
print("No root found."); return(NULL)
} else
while ((b - a)/2.0 > tol){
midpt= (a + b)/2.0
if (f(midpt) == 0){
return(midpt)
} else if (f(a)*f(midpt) < 0){
b = midpt
} else
a = midpt
}
return(midpt)
}
return(bisection_method(a,b,tol,funct_1))
}
Figured out some parameter combination that makes sense:
IS(1,1,1,4,5,1,.1,9,10^-4)
[1] 2.000023

type of a function in D

I'm interested in creating a function Derivative that returns a function that is the derivative of some function that is passed to it, at some point. However, I want to be able to specialize this so that, for specific functions, I can return the analytical solution.
So, I'm looking for something like this:
auto Derivate(alias Function)(x)
{ return (Function(x+h) - Function(x-h))/(2h);}
auto Derivate(BSpline!(k)(x))(x)
{ return k * BSpline!(k-1)(x) + x * BSpline!(k-1)(x); }
However, I currently have BSpline defined this way:
pure Real BSpline(int k : 0, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
return 1;
else
return 0;
}
pure Real BSpline(int k, Real)(scope Real x, scope const(Real)[] t)
{
if (t[0] <= x && x < t[k+1])
{
Real a = (x - t[0]) / (t[k] - t[0]);
Real b = (t[k+1] - x) / (t[k+1] - t[1]);
Real c = BSpline!(k-1,Real)(x, t[0..k+1]);
Real d = BSpline!(k-1,Real)(x, t[1..k+2]);
Real rv = (c?c*a:c) + (d?d*b:d);
return rv;
}
else
return 0;
}
So the type signature on BSpline is going to be Real function(Real,Real), which isn't differentiable from any other kind of function. Is the way to solve this to create a "BSpline" class with opCall defined? Or can I do some sort of typedef to identify this function?
Thanks!
To specialize a template, you have to use the : notation:
auto foo(alias F_, X_)(X_ x) {
/* code here ... */
}
auto foo(alias F_ : BSpline, X_)(X_ x) {
/* specialized version here */
}

R: Question about Optimizing - Invalid Function Value in Optimize

We have not been able to pinpoint what is causing the error of Invalid Function Value in Optimize in our Optimizing code. If you could offer any insight, it would be appreciated.
H_fun <- function(c)
{
val = -current_c_weight*c - X_counts%*%log(
exp(rep(c,length(current_Theta))*current_Theta) -
current_elongation_rates )
print('#########iteration display#############')
print('c')
print(c)
print('val')
print(val)
print('current_c_weight')
print(current_c_weight)
print('current_Theta')
print(current_Theta)
print('current_elongation_rates')
print(current_elongation_rates)
}
#...snip...
# minimize -H(c) without the non-negativity constraint
#tmp = optim(c(0,1),H_fun,NULL, method = "BFGS", hessian = TRUE);
tmp = optimize(H_fun,interval = c(0,1));
Here is a link to the code:
http://www.text-upload.com/read.php?id=102950&c=8605046
Are you sure H_fun is returning a one-dimensional value?
Look at fcn1() in the R optimize() source code:
static double fcn1(double x, struct callinfo *info)
{
SEXP s;
REAL(CADR(info->R_fcall))[0] = x;
s = eval(info->R_fcall, info->R_env);
switch(TYPEOF(s)) {
case INTSXP:
if (length(s) != 1) goto badvalue;
if (INTEGER(s)[0] == NA_INTEGER) {
warning(_("NA replaced by maximum positive value"));
return DBL_MAX;
}
else return INTEGER(s)[0];
break;
case REALSXP:
if (length(s) != 1) goto badvalue;
if (!R_FINITE(REAL(s)[0])) {
warning(_("NA/Inf replaced by maximum positive value"));
return DBL_MAX;
}
else return REAL(s)[0];
break;
default:
goto badvalue;
}
badvalue:
error(_("invalid function value in 'optimize'"));
return 0;/* for -Wall */
}
goto badvalue occurs if length is not 1. Also, the package summary states that optimize() works on a one-dimensional unconstrained function.

Resources