How to call function on all items in a list? - dart

Is there an idiomatic way to apply a function to all items in a list ?
For example, in Python, say we wish to capitalize all strings in a list, we can use a loop :
regimentNames = ['Night Riflemen', 'Jungle Scouts', 'The Dragoons', 'Midnight Revengence', 'Wily Warriors']
# create a variable for the for loop results
regimentNamesCapitalized_f = []
# for every item in regimentNames
for i in regimentNames:
# capitalize the item and add it to regimentNamesCapitalized_f
regimentNamesCapitalized_f.append(i.upper())
But a more concise way is:
capitalizer = lambda x: x.upper()
regimentNamesCapitalized_m = list(map(capitalizer, regimentNames)); regimentNamesCapitalized_m
What is an equivalent way to call a function on all items in a list in Dart ?

If you want to apply a function to all items in a List (or Iterable) and collect the results, Dart provides an Iterable.map function that is equivalent to Python's map:
// Dart
regimentNamesCapitalized_m = regimentNames.map((x) => x.toUpperCase()).toList();
Python also provides list comprehensions, which usually are considered more Pythonic and often are preferred to the functional approach:
# Python
regimentNamesCapitalized_m = [x.upper() for x in regimentNames]
Dart's equivalent of Python's list comprehensions is collection-for:
// Dart
regimentNamesCapitalized_m = [for (var x in regimentNames) x.toUpperCase()];
If you're calling a function for its side-effect and don't care about its return value, you could use Iterable.forEach instead of Iterable.map. In such cases, however, I personally prefer explicit loops:
I think they're more readable by virtue of being more common.
They're more flexible. You can use break or continue to control iteration.
They might be more efficient. .forEach involves an extra function call per iteration to invoke the supplied callback.

The answer seems to be to use anonymous functions, or pass a function to a lists forEach method.
Passing a function:
void capitalise(var string) {
var foo = string.toUpperCase();
print(foo);
}
var list = ['apples', 'bananas', 'oranges'];
list.forEach(capitalise);
Using an anonymous function:
list.forEach((item){
print(item.toUpperCase());
});
If the function is going to be used only in one place, I think its better to use the anonymous function, as it is easy to read what is happening in the list.
If the function is going to be used in multiple places, then its better to pass the function instead of using an anonymous function.

Related

How to write a recursive anonymous function in Dart

Lets say I wanted to write a recursive anonymous function to calculate factorial values.
print(((int a) => a == 1? 1 : a * this(a - 1))(4));
I would expect this to print 24, which is 4! (this function is obviously prone to issues with negative numbers, but that's beside the point)
The problem is that this doesn't refer to the anonymous function in order to make a recursive call.
Is this something that's possible in dart? I've seen it in python before, where a function is assigned to a variable with the walrus operator ( := ) and is also recursive.
Here is an example that creates a list of the average value on each level of a binary tree:
return (get_levels := lambda l: ([mean(node.val for node in l)] + get_levels([child for node in l for child in [node.left, node.right] if child])) if l else [])([root])
As you can see, the lambda is called get_levels. It calculates the average of the current level, then makes a recursive call on the next level of the binary tree and appends it to the list of previous level averages.
The closest that I could come up with is this:
var getLevels;
List<double> averageOfLevels(TreeNode? root) {
return root == null ? [] : (getLevels = (List<TreeNode> level) => level.isNotEmpty ? <double>[level.map((node) => node.val).fold(0, (int l, int r) => l+r) / level.length] + getLevels([for(var node in level) ...[node.left, node.right]].whereType<TreeNode>().toList()) : <double>[])([root]);
}
But, as you can see, this required an additional line where the variable is defined ahead of time.
Is it possible to achieve something more similar to the python example using callable classes?
There's a classic Lisp/Scheme problem of how to create a recursive lambda. The same technique of creating one anonymous function that takes itself as an argument and then using another anonymous function to pass the first anonymous function to itself can be applied to Dart (albeit by sacrificing some type-safety; I can't think of a way to strongly type a Function that takes its own type as an argument). For example, a recursive factorial implementation:
void main() {
var factorial = (Function f, int x) {
return f(f, x);
}((Function self, int x) {
return (x <= 1) ? 1 : x * self(self, x - 1);
}, 4);
print('4! = $factorial'); // Prints: 4! = 24
}
All that said, this seems like a pretty contrived, academic problem. In practice, just create a named function. It can be a local function if you want to avoid polluting a global namespace. It would be far more readable and maintainable.
Is it possible to achieve something more similar to the python example using callable classes?
I'm not sure where you're going with that since Dart neither allows defining anonymous classes nor local classes, so even if you made a callable class, it would violate your request for being anonymous.

Dart - When To Use Collection-For-In vs .Map() on Collections

Both the collection-for-in operation and .map() method can return some manipulation of elements from a previous collection. Is there ever any reason to prefer using one over the other?
var myList = [1,2,3];
var alteredList1 = [for(int i in myList) i + 2]; //[3,4,5]
var alteredList2 = myList.map((e) => e + 2).toList(); //[3,4,5]
Use whichever is easier and more readable.
That's a deliberately vague answer, because it depends on what you are doing.
Any time you have something ending in .toList() I'd at least consider making it into a list literal. If the body of the map or where is simple, you can usually rewrite it directly to a list literal using for/in (plus if for where).
And then, sometimes it gets complicated, you need to use the same variable twice, or the map computation uses a while loop, or something else doesn't just fit into the list literal syntax.
Then you can either keep the helper function and do [for (var e in something) helperFunction(e)] or just do something.map((e) { body of helper function }).toList(). In many cases the latter is then more readable.
So, consider using a list literal if your iterable code ends in toList, but if the literal gets too convoluted, don't feel bad about using the .map(...).toList() approach.
Readability is all that really matters.
Not an expert but personally I prefer the first method. Some reasons:
You can include other elements (independent from the for loop) in the same list:
var a = [1, 2, 3];
bool include5 = true;
var b = [
1,
for (var i in a) i + 1,
if (include5) 5,
];
print(b); // [1, 2, 3, 4, 5]
Sometimes when mapping models to a list of Widgets the .map().toList() method will produce a List<dynamic>, implicit casting won't work. When you come across such an error just avoid the second method.

arithemetic on multiple return values lua

Is it possible to perform arithmetic on multiple values in Lua.
I am using Lua for windows 5.1.4.
Currently I have to put the multiple values into a table and then unpack them, and I would like to be able to skip that step.
Is it possible.
Here is what I currently have:
function numsToStr(...)
local nums = {}
for i,v in ipairs({...}) do
nums[i] = v + string.byte('A') - 1
end
return string.char(unpack(nums))
end
What I want is to be able to do this
function numsToStr(...)
return string.char(...+string.byte('A')-1)
end
No, it is not possible to do arithmetic on multiple values in Lua.
It's not possible to do "directly", but you can implement "map" function, similar to what you've done. Some relevant resources: Short anonymous functions, thread on Perl-like map/grep functions, and map and other functions. Also take a look at list comprehensions in Penlight.

Some question about "Closure" in Lua

Here's my code, I confuse the local variable 'count' in the return function(c1,c2) with memory strack and where does they store in?
function make_counter()
local count = 0
return function()
count = count + 1
return count
end
end
c1 = make_counter()
c2 = make_counter()
print(c1())--print->1
print(c1())--print->2
print(c1())--print->3
print(c2())--print->1
print(c2())--print->2
in the return function(c1,c2) with memory strack and where does they store in?
It's stored in the closure!
c1 is not a closure, it is the function returned by make_counter(). The closure is not explicitly declared anywhere. It is the combination of the function returned by make_counter() and the "free variables" of that function. See closures # Wikipedia, specifically the implementation:
Closures are typically implemented with a special data structure that contains a pointer to the function code, plus a representation of the function's lexical environment (e.g., the set of available variables and their values) at the time when the closure was created.
I'm not quite sure what you're asking exactly, but I'll try to explain how closures work.
When you do this in Lua:
function() <some Lua code> end
You are creating a value. Values are things like the number 1, the string "string", and so forth.
Values are immutable. For example, the number 1 is always the number 1. It can never be the number two. You can add 1 to 2, but that will give you a new number 3. The same goes for strings. The string "string" is a string and will always be that particular string. You can use Lua functions to take away all 'g' characters in the string, but this will create a new string "strin".
Functions are values, just like the number 1 and the string "string". Values can be stored in variables. You can store the number 1 in multiple variables. You can store the string "string" in multiple variables. And the same goes for all other kinds of values, including functions.
Functions are values, and therefore they are immutable. However, functions can contain values; these values are not immutable. It's much like tables.
The {} syntax creates a Lua table, which is a value. This table is different from every other table, even other empty tables. However, you can put different stuff in tables. This doesn't change the unique value of the table, but it does change what is stored within that table. Each time you execute {}, you get a new, unique table. So if you have the following function:
function CreateTable()
return {}
end
The following will be true:
tableA = CreateTable()
tableB = CreateTable()
if(tableA == tableB) then
print("You will never see this")
else
print("Always printed")
end
Even though both tableA and tableB are empty tables (contain the same thing), they are different tables. They may contain the same stuff, but they are different values.
The same goes for functions. Functions in Lua are often called "closures", particularly if the function has contents. Functions are given contents based on how they use variables. If a function references a local variable that is in scope at the location where that function is created (remember: the syntax function() end creates a function every time you call it), then the function will contain a reference to that local variable.
But local variables go out of scope, while the value of the function may live on (in your case, you return it). Therefore, the function's object, the closure, must contain a reference to that local variable that will cause it to continue existing until the closure itself is discarded.
Where do the values get stored? It doesn't matter; only the closure can access them (though there is a way through the C Lua API, or through the Lua Debug API). So unlike tables, where you can get at anything you want, closures can truly hide data.
Lua Closures can also be used to implement prototype-based classes and objects. Closure classes and objects behave slightly differently than normal Lua classes and their method of invocation is somewhat different:
-- closure class definition
StarShip = {}
function StarShip.new(x,y,z)
self = {}
local dx, dy, dz
local curx, cury, curz
local engine_warpnew
cur_x = x; cur_y = y; cur_z = z
function setDest(x,y,z)
dx = x; dy=y; dz=z;
end
function setSpeed(warp)
engine_warpnew = warp
end
function self.warp(x,y,z,speed)
print("warping to ",x,y,x," at warp ",speed)
setDest(x,y,z)
setSpeed(speed)
end
function self.currlocation()
return {x=cur_x, y=cur_y, z=cur_z}
end
return self
end
enterprise = StarShip.new(1,3,9)
enterprise.warp(0,0,0,10)
loc = enterprise.currlocation()
print(loc.x, loc.y, loc.z)
Produces the following output:
warping to 0 0 0 at warp 10
1 3 9
Here we define a prototype object "StarShip" as an empty table.
Then we create a constructor for the StarShip in the "new" method. The first thing it does is create a closure table called self that contains the object's methods. All methods in the closure (those defined as 'function self.') are "closed" or defined for all values accessible by the constructor. This is why it's called a closure. When the constructor is done it returns the closure object "return self".
A lot more information on closure-based objects is available here:
http://lua-users.org/wiki/ObjectOrientationClosureApproach

Call a function from its name as a string in f#

I thought that I might be able to do this with quotations - but I can't see how.
Should I just use a table of the functions with their names - or is their a way of doing this?
Thanks.
For more info......
I'm calling a lot of f# functions from excel and I wondered if I could write a f# function
let fs_wrapper (f_name:string) (f_params:list double) =
this bit calls fname with f_params
and then use
=fs_wrapper("my_func", 3.14, 2.71)
in the sheet rather than wrap all the functions separately.
You'll need to use standard .NET Reflection to do this. Quotations aren't going to help, because they represent function calls using standard .NET MethodInfo, so you'll need to use reflection anyway. The only benefit of quotations (compared to naive reflection) is that you can compile them, which could give you better performance (but the compilation isn't perfect).
Depending on your specific scenario (e.g. where are the functions located), you'd have to do something like:
module Functions =
let sin x = sin(x)
let sqrt y = sqrt(y)
open System.Reflection
let moduleInfo =
Assembly.GetExecutingAssembly().GetTypes()
|> Seq.find (fun t -> t.Name = "Functions")
let name = "sin"
moduleInfo.GetMethod(name).Invoke(null, [| box 3.1415 |])
Unless you need some extensibility or have a large number of functions, using a dictionary containing string as a key and function value as the value may be an easier option:
let funcs =
dict [ "sin", Functions.sin;
"sqrt", Functions.sqrt ]
funcs.[name](3.1415)
There are many methods but one way is to use Reflection, for instance:
typeof<int>.GetMethod("ToString", System.Type.EmptyTypes).Invoke(1, null)
typeof<int>.GetMethod("Parse", [|typeof<string>|]).Invoke(null, [|"112"|])
GetMethod optionally takes an array of types that define the signature, but you can skip that if your method is unambiguous.
Following up on what Thomas alluded to, have a look at Using and Abusing the F# Dynamic Lookup Operator by Matthew Podwysocki. It offers a syntactically clean way for doing dynamic lookup in F#.

Resources