Combine filter and map in Xtend collections - xtend

Given some iterable variable v and a type T I often find myself writing code such as
v.filter[it instanceof T].map[it as T]
Does there exist some helper which does the same functionality in a single step?

You may want to use v.filter(T) (or the legacy syntax v.filter(typeof(T))) which is Xtend's syntax for the Java equivalent v.filter(T.class).

Related

Tuple without last element with correct type

Is it possible to remove the last element from a tuple in typesafe manner for arbitrary arity?
I want something like this:
[A,B,C] abc = [a,b,c];
[A,B] ab = removeLast(abc);
No, unfortunately it's not possible, the reason being that a tuple type is represented within the type system as a linked list of instantiations of Tuple, but the type system can't express loops or recursion within the signature of a function. (And having loops/recursion would almost certainly make the type system undecidable.)
One way we could, in principle, solve this in future would be to have a built-in primitive type function that evaluates the last element type of a tuple type.
By "primitive" type function, I mean a type function that can't be written in the language itself, but is instead provided as a built-in by the compiler.
Ceylon doesn't currently have any of these sorts of primitive type functions, but there are a couple of other similar problems which could be solved in this manner.

Equivalent of C++ std::vector, std::deque and std::map in FreePascal

What's equivalent of std::vector, std::deque and std::map in ObjectPascal (FreePascal compiler)?
In brief:
(vector) is an auto-resizing contiguous array
(deque) is an auto-sizing hybrid array of arrays giving near O(1) random
access while allowing O(1) push/pop from either end
(map, unordered_map) is an associative array
In general it is not logical to assume there are direct substitutes in some different language.
Currently FPC generics are a mix of old school C++ like generics (based on token replay), and Delphi more .NET styled generics (fully declarative, but more limited for value types for languages without autoboxing).
Anyway, I'll give it a try:
TList or its generic variants. (TList<> in Delphi or fgl.Tf*List in unit fgl)
No standard type, I have an array of array generic class, but that is optimized to avoid some of the problems of ordered Lists (insertion performance) while still being an ordered type. I've put it on http://www.stack.nl/~marcov/genlight.pas, maybe it gives you some ideas on how to approach the problem.
None yet. TDictionary once http://bugs.freepascal.org/view.php?id=27206 is committed. Currently usually TAVLTree is used.
There is also some generics including a simple deque in packages/fcl-stl, I suggest you check it out.

How to define my function from a string?

This is normal definition of some function as I know:
real function f(x)
real x
f = (sin(x))**2*exp(-x)
end function f
But I want to define a function from some string, for example the program will ask me to write it, and then it will define the function f in a program. Is this possible in Fortran?
What you are looking for is possible in reflective programming languages, and is not possible in Fortran.
Quote from the link above:
A language supporting reflection provides a number of features available at runtime that would otherwise be very obscure to accomplish in a lower-level language. Some of these features are the abilities to:
Discover and modify source code constructions (such as code blocks, classes, methods, protocols, etc.) as a first-class object at runtime.
Convert a string matching the symbolic name of a class or function into a reference to or invocation of that class or function.
Evaluate a string as if it were a source code statement at runtime.
Create a new interpreter for the language's bytecode to give a new meaning or purpose for a programming construct.
I worked on a project once that tried to achieve something similar. We read in a string that contained a string with named variables and mathematical operations (a function if you will). In this string the variables then got replaced by their numerical values and the terms were evaluated.
The basic idea is not to too difficult, but it requires a lot of string manipulations - and it is not a function in the context of a programming language.
We did it like this:
Recursively divide the string at +,-,/,*, but remember to honor brackets
If this is not possible (without violating bracketing), evaluate the remaining string:
Does it contain a mathematical expression like cos? Yes => recurse into arguments
No => evaluate the mathematical expression (no variables allowed, but they got replaced)
This works quite well, but it requires:
Splitting strings
Matching in strings
Replacing strings with other strings, etc.
This is not trivial to do in Fortran, so if you have other options (like calling an external tool/script that returns the value), I would look into that - especially if you are new to Fortran!

What are better ways to create a method that takes many arguments? (10+?)

I was looking at some code of a fellow developer, and almost cried. In the method definition there are 12 arguments. From my experience..this isn't good. If it were me, I would have sent in an object of some sort.
Is there another / more preferred way to do this (in other words, what's the best way to fix this and explain why)?
public long Save (
String today,
String name,
String desc,
int ID,
String otherNm,
DateTime dt,
int status,
String periodID,
String otherDt,
String submittedDt
)
ignore my poor variable names - they are examples
It highly depends on the language.
In a language without compile-time typechecking (e.g. python, javascript, etc.) you should use keyword arguments (common in python: you can access them like a dictionary passed in as an argument) or objects/dictionaries you manually pass in as arguments (common in javascript).
However the "argument hell" you described is sometimes "the right way to do things" for certain languages with compile-time typechecking, because using objects will obfuscate the semantics from the typechecker. The solution then would be to use a better language with compile-time typechecking which allows pattern-matching of objects as arguments.
Yes, use objects. Also, the function is probably doing too much if it needs all of this information, so use smaller functions.
Use objects.
class User { ... }
User user = ...
Save(user);
It decision provides easy way for adding new parameters.
It depends on how complex the function is. If it does something non-trivial with each of those arguments, it should probably be split. If it just passes them through, they should probably be collected in an object. But if it just creates a row in a table, it's not really big deal. It's less of a deal if your language supports keyword arguments.
I imagine the issue you're experiencing is being able to look at the method call and know what argument is receiving what value. This is a pernicious problem in a language like Java, which lacks something like keyword arguments or JSON hashes to pass named arguments.
In this situation, the Builder pattern is a useful solution. It's more objects, three total, but leads to more comprehensible code for the problem you're describing. So the three objects in this case would be as such:
Thing: stateful entity, typically immutable (i.e. getters only)
ThingBuilder: factory class, creates a Thing entity and sets its values.
ThingDAO: not necessary for using the Builder pattern, but addresses your question.
Interaction
/*
ThingBuilder is a static inner class of Thing, where each of its
"set" method calls returns the ThingBuilder instance being worked with
while the final "build()" call returns the instantiated Thing instance.
*/
Thing thing = Thing.createBuilder().
.setToday("2012/04/01")
.setName("Example")
// ...etc...
.build();
// the Thing instance as get methods for each property
thing.getName();
// get your reference to thingDAO however it's done
thingDAO.save(thing);
The result is you get named arguments and an immutable instance.

How do XQuery function namespaces work?

EDIT
I want to group together related functions to show that they are related.
If I have local:f1() and local:f2() then I could just change their names to local:menu-f1() and local:menu-f2() but is there a mechanism in the XQuery language to group related functions?
OP
I am very excited to discover that XQuery functions can be declared in a namespace other than local:. Where can I find info about how this works?
Having always declared functions in this way;
declare function local:foo() {
3+4
};
.. and used them in this way;
local:foo()
.. I discover that they can be declared like this;
declare namespace baz = "fred:bloggs";
declare function baz:foo() {
3+4
};
.. and used like this;
baz:foo()
But I can only find reference-like information about declare namespace and declare function separately, not tutorial-like information about how XQuery function namespaces work in general.
Is there a newbie guide to XQuery function namespaces?
I'm using a Saxon processor - XQuery 1.0.
What you are probably using are normal XQuery namespaces - what you probably are looking for are modules. You can put a bunch of functions in its own module namespace like this:
module namespace foo = "http://www.myurl.com/foo";
declare function foo:bar($args as item()*) as item()* {
() (: do something cool :)
};
Afterwards you can import the module in you main query and call the function:
import module namespace foo = "http://www.myurl.com/foo";
foo:bar(<my-element/>)
The problem is, that it is not standardized, how the processor has to find the query. And I don't know how Saxon implements the module resolving mechanism (you should look into the documentation and/or write to the Saxon mailing list).
But most XQuery processors look at the path given by an "at" clause relative from the location of the query. So to have something that should work on most implementations: For example you could store the module in a file named foo.xq and place it into the same directory than your main query and then for the module import you would write:
import module namespace foo = "http://www.myurl.com/foo" at "foo.xq";
which gives a hint to the XQuery engine where it should look for the module.
You can find some (not a lot at the moment) documentation about this stuff at http://www.xquery.me/ - hope this helps.
EDIT
Ok I see, you only want to group your functions. To do that you already figured out everything you need to know. But I still want to emphasize that splitting your query up into modules would probably be the better solution for your use-case (it's just somehow nicer, since your have more modularity and in the upcoming XQuery 3.0 recommendation you will even have the possibility to put stuff like private functions and variables in there). But if your query does not get big, your solution is of course also ok.
You can think about XML namespaces the same way you would think about namespaces in C++. In XQuery, functions, elements, collections, variables, attributes etc can be in an own namespace (again - like in C++). There are some implicitely defined namespaces like xs (the XML Schema namespace where you can find the data types like boolean, integer etc), local (a namespace where you can put in functions so that you are not forced to define your own namespace in a main query), fn (where all functions from the "XQuery 1.0 and XPath 2.0 functions and operators" recommendation are defined). But the prefix of this function is only an alias - you can use whatever you want.
So let's say you have the following code in the prolog of your query:
declare namespace blubb = "http://www.w3.org/2001/XMLSchema";
blubb:integer would be exactly the same type than xs:integer - the same holds for functions:
declare namespace l = "http://www.w3.org/2005/xquery-local-functions";
With declaring that you can access every function in the local namespace with the "l" prefix (so l:bar() if local:bar() exists).
If you do not type a prefix, XQuery assumes that this function is in the "fn" namespace. This is why bot
fn:concat("Hello ", "World!")
and
concat("Hello ", "World!")
are equivalent. You can change this behavior. You could include this line into the prolog:
declare default function namespace "http://www.w3.org/2005/xquery-local-functions";
which would tell the XQuery processor that you do not want to prefix local functions (so bar() would be equivalent to local:bar()).
I am not sure if I answered your questions or at least was able to bring in some clarity. I do not know about a tutorial for that (since in the beginning it is somehow confusing but in the end you realize that there is not a lot to say about since the mechanisms are much simpler than they look in the first place). The document where I always look up stuff is the recommendation at http://www.w3.org/TR/xquery/
If this does not help you please try to qualify and I can try again with an explanation..