What should happen when a generator function is assigned? [closed] - language-agnostic

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
If I have a programming language with first class functions. What should the semantics be when a generator function is shared?
For example:
var f = function() {
foreach (i in 0..42)
yield i;
}
int a = f(); // 0
int b = f(); // 1
// Assigning the generator function
var g = f;
int c = g(); // ??
int d = f(); // ??
I can imagine three things:
c == 2, d == 3 meaning that the generator function is shared
c == 0, d == 2 meaning that a new generator function is created, with the values initialized
c == 2, d == 2 meaning that a new generator function is created by copying the current state of the generator
The best answer in my opinion, would provide the most compelling argument to do one mechanism or another. Often I find that prior art is the most persuasive argument.

If you have reference semantics in your language, and assignment is usually reference assignment, then you want option 1.
This is what happens in Python, where generates are objects, and assignment is reference assignment (even though you invoke .next() to retrieve the next value, rather than "calling" the generator).
Here is a brief demonstration how this behaves in Python:
>>> def gen():
... for i in range(42):
... yield i
...
>>> f = gen().next
>>> a = f()
>>> b = f()
>>> g = f
>>> c = g()
>>> d = f()
>>> a, b, c, d
(0, 1, 2, 3)

Related

Uppercase in name of a function in Julia

I am fairly new to Julia and got confused with the following code. After a function LucasTree is defined, it is used again as lt. Does Julia have some kind of role where I can recall a function using the uppercase abbreviation? If so, where can I find a nice reference for this feature?
function LucasTree(;γ = 2.0,
β = 0.95,
α = 0.9,
σ = 0.1,
grid_size = 100)
ϕ = LogNormal(0.0, σ)
shocks = rand(ϕ, 500)
# build a grid with mass around stationary distribution
ssd = σ / sqrt(1 - α^2)
grid_min, grid_max = exp(-4ssd), exp(4ssd)
grid = range(grid_min, grid_max, length = grid_size)
# set h(y) = β * int u'(G(y,z)) G(y,z) ϕ(dz)
h = similar(grid)
for (i, y) in enumerate(grid)
h[i] = β * mean((y^α .* shocks).^(1 - γ))
end
return (γ = γ, β = β, α = α, σ = σ, ϕ = ϕ, grid = grid, shocks = shocks, h = h)
end
function lucas_operator(lt, f)
# unpack input
#unpack grid, α, β, h = lt
z = lt.shocks
Af = LinearInterpolation(grid, f, extrapolation_bc=Line())
Tf = [ h[i] + β * mean(Af.(grid[i]^α .* z)) for i in 1:length(grid) ]
return Tf
end
No, this does not exist. It would be too nonunique to be practical, and moreover function names in Julia by convention should be entirely lowercase (structs/types can be CamelCase, but not functions, with the possible exception of constructors*).
In any case, all that is happening here in the code you have posted is that the function lucas_operator takes two arguments, lt and f, which can then be used within that lucas_operator function. These could in principle be anything, and regardless of what they are named outside the scope of the function, they will be named lt and f within the scope of the function. So for example:
function example(foo, bar)
return foo(2*bar)
end
if you then call
example(somereallylongfunctionname, somevariable)
then that will return the equivalent of
somereallylongfunctionname(2*somevariable)
or similarly
example(SomeImproperlyCapitalizedFunction, somevariable)
# equivalent to SomeImproperlyCapitalizedFunction(2*somevariable)
in either case, regardless of its name outside the scope of the example function, the first argument passed to the function will be known as foo within the function.
* Aside about constructors: that would be a function that is used to construct a custom type. This doesn't quite do that, but it does return an instance of a NamedTuple which then seems to be treated somewhat like a type/struct in the subsequent code, so perhaps it could be counted as a constructor.

Fortran function for geometric series [duplicate]

This question already has answers here:
What is the purpose of result variables in Fortran?
(1 answer)
Does Fortran preserve the value of internal variables through function and subroutine calls?
(3 answers)
Fortran assignment on declaration and SAVE attribute gotcha
(2 answers)
Closed 3 years ago.
I am implementing this equation with a Fortran function.
Write call in function (g) consistently returns 6, but when I call function in program (z) output depends, e.g.,
-2123950080
-529463296
929961984.
Why g and z are not the same? What should I change in function to accomplish geometric series calculation?
function geomSeries(n)
implicit none
integer :: i, n, g = 0, x = 1, geomSeries
g = 1 + x
do i = 2, n
g = g + x**i
end do
write (*,*) g
return
end function geomSeries
program geomFunc
implicit none
integer :: n = 5, geomSeries, z
z = geomSeries(n)
write (*,*) z
end program geomFunc
P.S. Ideally I would like it to be pure function, as I don't see how it produces side effects, but haven't managed to compile it that way (why?).

How to draw a line using X, Y, Z coordinates from a csv or txt file? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
and I'm having difficulty to drawing a line on the screen using the X, Y, Z coordinates of a CSV or TXT file. I tried with the line render and also with swipe trail, but I could not. Thanks for your help
Read a file e.g using StreamReader.ReadToEnd
var fileContent = "";
(using var reader = new StreamReader(path))
{
fileContent = reader.ReadToEnd();
}
Assuming a CSV/txt content like
23.46, 1.0, 2.4
0.003, 7.038, 3
...
Parse the content e.g. using SplitCSVLine from CSVReader
private static string[] SplitCsvLine(string line)
{
return (from System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(line,
#"(((?<x>(?=[,\r\n]+))|""(?<x>([^""]|"""")+)""|(?<x>[^,\r\n]+)),?)",
System.Text.RegularExpressions.RegexOptions.ExplicitCapture)
select m.Groups[1].Value).ToArray();
}
use it together with float.TryParse(string, out float) like
var lines = fileContent.Split('/n');
var points = new List<Vector3>();
foreach(var line in lines)
{
var parts = SplitCsvLine(line);
float x = float.TryParse(parts[0], out x) ? x : 0;
float y = float.TryParse(parts[1], out y) ? y : 0;
float z = float.TryParse(parts[2], out z) ? z : 0;
points.Add(new Vector3(x, y, z));
}
where
float x = float.TryParse(parts[0], out x) ? x : 0;
is a short form of writing
float x;
if(!float.TryParse(parts[0], out x))
{
x = 0;
// Alternatively you could also declare this point as invalid
// and not add this point at all
continue;
}
or, if you know the content will only exactly contain those numeric symbols and commas, no special characters, you could also simply use
var parts = line.Split(',');
And finally apply those points e.g. to a LineRenderer using SetPositions
GetComponent<LineRenderer>().SetPositions(points);
There might be more efficient options though.

Applying a function to multiple rows of a data frame where the row is an argument in the function in R

Apologies for the rather long name, but I wanted to be specific. I am rather new to R and coding so please go easy on me.
I have a function as follows:
myfun = function(x, y, g) {return(1 / (1 + exp(y*g%*%x)))}
where x is any data frame with n rows and d columns, y is a scalar and integer, and g is a vector of length d (i.e. same as x). I want to run this function for each row of x without using loops.
I have tried various function in the apply family similar to the code below:
apply(x = a, 1, myfun(y = 1, g = b)
where a is a 3x3 data frame and b is a vector 3 elements long. The above code gives an error that I am missing an argument from myfun, but I am obviously clueless on what to try.
Thanks for any help in advance!
Edit: My actual data frame is huge, sparse, and not very straight forward (I think), so I will include an example data frame and other variables:
a = data.frame(c1 = seq(1,3,1), c2 = seq(4,6,1), c3 = seq(7,9,1))
b = c(1,2,3)
c = 1
Also, I think I may have not clearly stated an important piece of information. I want to actually do a summation of myfun over all the rows and values of b, so I actually want the following:
answer = myfun(a[1,], c, b[1]) + myfun(a[2,], c, b[2]) + myfun(a[3,], c, b[3])
In other words, a[1,] should be applied to myfun with b[1] as they are grouped together. I also made an edit to the function above because I forgot to include return(). Hopefully, this makes things more clear. Apologies for the confusion!

I want to know SML code's return value

I have SML code.
fun f(0) = 1
| f(1) = raise Odd
| f(3) = f(3-2)
| f(n) = (f(n-2) handle Odd => ~n)
The problem is that when f(11) is called f(9),f(7),...... are called.
And there is a precondition that "if f calls g and g raises an exception that f does not handle, then activation record of f is popped off the stack without returning control to the function f.".
What is returning value? I think it is -5, but can't be sure about that.