Function as an argument in Erlang - functional-programming

I'm trying to do something like this:
-module(count).
-export([main/0]).
sum(X, Sum) -> X + Sum.
main() ->
lists:foldl(sum, 0, [1,2,3,4,5]).
but see a warning and code fails:
function sum/2 is unused
How to fix the code?
NB: this is just a sample which illustrates problem, so there is no reason to propose solution which uses fun-expression.

Erlang has slightly more explicit syntax for that:
-module(count).
-export([main/0]).
sum(X, Sum) -> X + Sum.
main() ->
lists:foldl(fun sum/2, 0, [1,2,3,4,5]).
See also "Learn you some Erlang":
If function names are written without a parameter list then those names are interpreted as atoms, and atoms can not be functions, so the call fails.
...
This is why a new notation has to be added to the language in order to let you pass functions from outside a module. This is what fun Module:Function/Arity is: it tells the VM to use that specific function, and then bind it to a variable.

Related

plotting a python function that uses an array

In sagemath, I would like to plot the following function foo (Coef is an array that is big enough) :
def foo(x):
x_approx = floor (x*4)
return Coef[x_approx]
I wanted to use the command plot(foo(x), (x,0,0.1)).
But I got the error unable to convert floor(4*x) to an integer.
Whereas when `foo is not using an array, it works:
def foo(x):
x_approx = floor (x*4)
return 4*x_approx
Use plot(foo, (x, 0, 0.1)) instead (that is, replace foo(x) with foo). If you use foo(x), then Sage tries to evaluate foo(x) first, in which case it treats x as a symbolic variable and can't turn it into a number to plot. If you use foo, then it knows to treat it as a plottable/callable function, and it does the right thing.
Edit: I think the issue is that for plotting, Sage requires a certain type of function, a symbolic function, and using a Python construct like Coef[...] doesn't fit into that framework.

Call Arguments of Function inside Function / R language

I have a function:
func <- function (x)
{
arguments <- match.call()
return(arguments)
}
1) If I call my function with specifying argument in the call:
func("value")
I get:
func(x = "value")
2) If I call my function by passing a variable:
my_variable <-"value"
func(my_variable)
I get:
func(x = my_variable)
Why is the first and the second result different?
Can I somehow get in the second call "func(x = "value")"?
I'm thinking my problem is that the Environment inside a function simply doesn't contain values if they were passed by variables. The Environment contains only names of variables for further lookup. Is there a way to follow such reference and get value from inside a function?
In R, when you pass my_variable as formal argument x into a function, the value of my_variable will only be retrieved when the function tries to read x (if it does not use x, my_variable will not be read at all). The same applies when you pass more complicated arguments, such as func(x = compute_my_variable()) -- the call to compute_my_variable will take place when func tries to read x (this is referred to as lazy evaluation).
Given lazy evaluation, what you are trying to do is not well defined because of side effects - in which order would you like to evaluate the arguments? Which arguments would you like to evaluate at all? (note a function can just take an expression for its argument using substitute, but not evaluate it). As a side effect, compute_my_variable could modify something that would impact the result of another argument of func. This can happen even when you only passed variables and constants as arguments (function func could modify some of the variables that will be later read, or even reading a variable such as my_variable could trigger code that would modify some of the variables that will be read later, e.g. with active bindings or delayed assignment).
So, if all you want to do is to log how a function was called, you can use sys.call (or match.call but that indeed expands argument names, etc). If you wanted a more complete stacktrace, you can use e.g. traceback(1).
If for some reason you really wanted values of all arguments, say as if they were all read in the order of match.call, which is the order in which they are declared, you can do it using eval (returns them as list):
lapply(as.list(match.call())[-1], eval)
can't you simply
return paste('func(x =', x, ')')

Top level assignment

I was trying to create a function using a higher-order function in Erlang. To my surprisement, this seems to not be okay. Here's a simplified example of the error I'm getting.
-module(test).
-export([main/0]).
X = 1.
main() ->
io:format("~p~n", [X]).
And in erl:
> c(test).
test.erl:4: syntax error before: X
test.erl:7: variable 'X' is unbound
error
Do you have any idea what could be done to circumvent this?
There are no global variables in Erlang. You can use a function instead, like this for example:
-module(test).
-export([main/0]).
x() ->
1.
main() ->
io:format("~p~n", [x()]).
For something as simple as a literal 1 you could also define a preprocessor macro, like this:
-define(X, 1).
main() ->
io:format("~p~n", [?X]).
but given that your question mentions higher-order functions, you probably don't want to use the preprocessor.

How to write a sum function in F# using RProvider?

#r "RProvider.dll"
open RProvider
open RProvider.``base``
let add (x: float) (y: float) =
let sum = R.sum(x,y)
sum.Value
VS gives me the error "The field, constructor or member 'Value' is not defined"
I also tried passing a vector to R.sum
from the little existing documentation (https://github.com/BlueMountainCapital/FSharpRProvider/wiki/How-To) I can't figure what to do
The R.sum function seems to be a bit uglier to use, because it takes variable number of parameters and sums all of them (so the R type provider cannot infer what arguments it expects).
To get the result back, you'll need some extension methods:
open RDotNet
There are two options for calling such function - you can just give it the arguments (without specifying their names), which works well enough for R.sum:
// You can pass parameters as an explicit array
R.sum([| 2.0; 3.0 |]).AsNumeric() |> Seq.head
// Or you can use the fact that the function takes 'params' array
R.sum(1.0, 2.0).AsNumeric() |> Seq.head
If you want to specify the name of the parameters (not really needed here, but useful for other function), then you can build a structure representing "named parameters" for an R function and call it:
let nums = namedParams ["x", 2.0; "y", 3.0]
R.sum(nums).AsNumeric() |> Seq.head
Note that the situation is nicer for functions where the parameters can be statically inferred. E.g.:
R.mean(x=[1;2;3])

Guarantying assignment to a function's return value in OCaml

Coming to OCaml from Lisp, I find myself very confused about when functions return and when they don't. I miss my magic Quote! Thankfully, most of the time, OCaml appears to automagicly know when I want a function evaluated and when I don't. However, I frequently find myself trying to assign the return value of a function in a let expression, like the following.
let start = Sys.time in
(*
* do something here
*)
;
let ending = Sys.time in
Printf.printf "did something in %f seconds\n" (ending -. start)
but then ocamlc complains
Error: This Expression has type unit -> float
but an expression was expected of type float
Telling me that start and end are bound to Sys.time, not the return value of Sys.time.
Is this behavior I'm trying to get not OCamly? Do I want to be doing things another way? Am I just missing something completely obvious?
A function is evaluated when you apply it to an argument. I.e. when you do f, f never gets evaluated. When you do f x, f always gets evaluated. There's nothing magical about it.
As you correctly pointed out, Sys.time is a function (of type unit -> float) and let start = Sys.time just assigns that function to start.
To get the behavior you want simply do let start = Sys.time (), which applies the function Sys.time to the argument () (which is the only value of type unit).
You cannot call a function just by writing its name. If you just write a function's name, you're returning the function itself, not its return value. That error is telling you that the function takes a unit argument — i.e., you should write Sys.time () to actually apply the function and get the resulting float value.
To help people used to Lisp, I would say that there are only two evaluation rules in OCAML:
Delayed evaluation rule: A function value, such as fun x -> body, when not applied to any argument, will not be evaluated any further. (The evaluation of a function body is “delayed”.) Instead, the expression “body” is compiled into computer code. That computer code is the real “value” of the function expression, and the code will be run whenever the function is applied to an argument.
Eager evaluation rule: In evaluating f x, the argument x is evaluated first. (Functions are “eager to evaluate their arguments”.) Then the function expression f is evaluated, which generally yields a function value such as fun x -> body. (Here, body is not yet evaluated; only as much is evaluated that we get a function value fun x -> body. For example, f could be a complicated expression that yields such a function value as a result.) Finally, the body of the resulting function is applied to the actually computed value of the argument (i.e. the body is evaluated with x substituted by the computed value of the argument).
For this reason, you can implement "quote" in OCAML, if you want to delay the evaluation of some expression, only by putting it inside the body of a function expression. For example, if you have previously computed f by let f = fun x->x+1 and now you want to delay the evaluation of f 3, you can put this f 3 into the body of a function:
let delay_f () = f 3;;
Now you will get 4 only when you evaluate delay_f (). You can pass the value delay_f to another function, and f 3 will stay unevaluated until somebody evaluates delay_f ().

Resources