How to assign a function to an operator? - pascal

so i have a really simple function in my unit:
Function AzonosE(Const n1,n2:TNap):Boolean;
Begin
AzonosE:=n1=n2;
End;
i'd like to assign the('=') operator to this function, so that i can use this function in my main program this way : if n1=n2 (n1,n2:TNap;)

That's not standard Pascal functionality. OTOH, afaik neither is "CONST". You need to better specify your dialect/compiler.
In the case of Free Pascal, Niculare's reference to the relevant manual page is correct. It is afaik FPC specific though. For more practical applications it is best to have a look at the ucomplex unit in the RTL that defines a complex type.
Delphi afaik only allows it as part of structured type:
http://docwiki.embarcadero.com/RADStudio/XE3/en/Operator_Overloading_%28Delphi%29

Related

Is there an identity function in Ruby?

I'm currently writing a Ruby class that provides a menu of base lambdas that can be mixed-and-matched to create a new set of lambdas. (it's an evolutionary algorithm that requires a lot of customizing of the fitness function depending on the dataset)
The configuration fire where this happens it full of stuff like this
function_from_modifier.(base_function, either.(modifier_from.(case),->(x){x}) )
The identity function ->(x){x} pops up several times in the configuration file, and it looks ugly, so I was wondering if there is a more elegant way of doing this. Is something like Elixir's &(&1) possible in Ruby?
tl;dr summary: there is no identity function in the Ruby core or standard libraries. In fact, there are no functions (in the sense of pre-defined Proc instances) at all anywhere in the core or standard libraries.
First-class functions in Ruby are kind-of second-class (if that makes sense).
When Yukihiro "matz" Matsumoto first designed Ruby, he surveyed the standard libraries of other languages for uses of first-class and higher-order functions, and he found that the vast majority of uses were:
a single function argument
that is not stored, passed, or returned
that is only immediately invoked one or more times
A significant portion of higher-order functions where this is not true are control structures (e.g. if which takes a condition and two consequences), which however he wanted to model as built-in language constructs, not library functions.
Therefore, he decided to optimize Ruby for the common case that he identified, and created blocks.
Blocks are not first-class functions:
they aren't objects
you can't send messages to them
they can't be stored in variables
they can't be returned
they can't be freely passed as arguments, you can only pass at most one and only at a special place in the argument list
As a result, real (in the sense that they are actual objects) first-class functions (Procs) are in some sense second-class language features compared to blocks:
they are more expensive in memory
calling them is slower
they are more syntactically cumbersome to create
So, in essence, it is not surprising that you are running into limitations when trying to use Ruby the way you do: that's not what Ruby was designed for.
In the past, I used to carry around a helper library with constants such like this:
class Proc
Id = -> x { x }
end
But I stopped doing that. If I want to use Ruby, I use Ruby as an OO language, if I want to do fancy FP, I use Haskell or Scala or Clojure or Racket or …
There is no anonymous functions capture in ruby, because in OOP there are objects having methods defined on them, not functions.
The most similar call would be Object#itself, and while one might do method(:itself) instead of ->(x) { x }, it would not be exactly same for many reasons.
Why would not you just assign the anonymous function to the variable and use it instead, like λ = ->(x) { x } and then use λ everywhere?
Sidenote: using a bare function instead of the block in call to either looks like a bad design to me. Blocks are faster, and everywhere in the core lib ruby uses blocks in such a case.

Is there a way to make the compiler copy-paste entire methods for performance? [duplicate]

How do you do "inline functions" in C#? I don't think I understand the concept. Are they like anonymous methods? Like lambda functions?
Note: The answers almost entirely deal with the ability to inline functions, i.e. "a manual or compiler optimization that replaces a function call site with the body of the callee." If you are interested in anonymous (a.k.a. lambda) functions, see #jalf's answer or What is this 'Lambda' everyone keeps speaking of?.
Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using MethodImplOptions.AggressiveInlining value. It is also available in the Mono's trunk (committed today).
// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
1. Previously "force" was used here. I'll try to clarify the term. As in the comments and the documentation, The method should be inlined if possible. Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.
Inline methods are simply a compiler optimization where the code of a function is rolled into the caller.
There's no mechanism by which to do this in C#, and they're to be used sparingly in languages where they are supported -- if you don't know why they should be used somewhere, they shouldn't be.
Edit: To clarify, there are two major reasons they need to be used sparingly:
It's easy to make massive binaries by using inline in cases where it's not necessary
The compiler tends to know better than you do when something should, from a performance standpoint, be inlined
It's best to leave things alone and let the compiler do its work, then profile and figure out if inline is the best solution for you. Of course, some things just make sense to be inlined (mathematical operators particularly), but letting the compiler handle it is typically the best practice.
Update: Per konrad.kruczynski's answer, the following is true for versions of .NET up to and including 4.0.
You can use the MethodImplAttribute class to prevent a method from being inlined...
[MethodImpl(MethodImplOptions.NoInlining)]
void SomeMethod()
{
// ...
}
...but there is no way to do the opposite and force it to be inlined.
You're mixing up two separate concepts. Function inlining is a compiler optimization which has no impact on the semantics. A function behaves the same whether it's inlined or not.
On the other hand, lambda functions are purely a semantic concept. There is no requirement on how they should be implemented or executed, as long as they follow the behavior set out in the language spec. They can be inlined if the JIT compiler feels like it, or not if it doesn't.
There is no inline keyword in C#, because it's an optimization that can usually be left to the compiler, especially in JIT'ed languages. The JIT compiler has access to runtime statistics which enables it to decide what to inline much more efficiently than you can when writing the code. A function will be inlined if the compiler decides to, and there's nothing you can do about it either way. :)
Cody has it right, but I want to provide an example of what an inline function is.
Let's say you have this code:
private void OutputItem(string x)
{
Console.WriteLine(x);
//maybe encapsulate additional logic to decide
// whether to also write the message to Trace or a log file
}
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{ // let's pretend IEnumerable<T>.ToList() doesn't exist for the moment
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
OutputItem(y);
}
return result;
}
The compilerJust-In-Time optimizer could choose to alter the code to avoid repeatedly placing a call to OutputItem() on the stack, so that it would be as if you had written the code like this instead:
public IList<string> BuildListAndOutput(IEnumerable<string> x)
{
IList<string> result = new List<string>();
foreach(string y in x)
{
result.Add(y);
// full OutputItem() implementation is placed here
Console.WriteLine(y);
}
return result;
}
In this case, we would say the OutputItem() function was inlined. Note that it might do this even if the OutputItem() is called from other places as well.
Edited to show a scenario more-likely to be inlined.
Do you mean inline functions in the C++ sense? In which the contents of a normal function are automatically copied inline into the callsite? The end effect being that no function call actually happens when calling a function.
Example:
inline int Add(int left, int right) { return left + right; }
If so then no, there is no C# equivalent to this.
Or Do you mean functions that are declared within another function? If so then yes, C# supports this via anonymous methods or lambda expressions.
Example:
static void Example() {
Func<int,int,int> add = (x,y) => x + y;
var result = add(4,6); // 10
}
Yes Exactly, the only distinction is the fact it returns a value.
Simplification (not using expressions):
List<T>.ForEach Takes an action, it doesn't expect a return result.
So an Action<T> delegate would suffice.. say:
List<T>.ForEach(param => Console.WriteLine(param));
is the same as saying:
List<T>.ForEach(delegate(T param) { Console.WriteLine(param); });
the difference is that the param type and delegate decleration are inferred by usage and the braces aren't required on a simple inline method.
Where as
List<T>.Where Takes a function, expecting a result.
So an Function<T, bool> would be expected:
List<T>.Where(param => param.Value == SomeExpectedComparison);
which is the same as:
List<T>.Where(delegate(T param) { return param.Value == SomeExpectedComparison; });
You can also declare these methods inline and asign them to variables IE:
Action myAction = () => Console.WriteLine("I'm doing something Nifty!");
myAction();
or
Function<object, string> myFunction = theObject => theObject.ToString();
string myString = myFunction(someObject);
I hope this helps.
The statement "its best to leave these things alone and let the compiler do the work.." (Cody Brocious) is complete rubish. I have been programming high performance game code for 20 years, and I have yet to come across a compiler that is 'smart enough' to know which code should be inlined (functions) or not. It would be useful to have a "inline" statement in c#, truth is that the compiler just doesnt have all the information it needs to determine which function should be always inlined or not without the "inline" hint. Sure if the function is small (accessor) then it might be automatically inlined, but what if it is a few lines of code? Nonesense, the compiler has no way of knowing, you cant just leave that up to the compiler for optimized code (beyond algorithims).
There are occasions where I do wish to force code to be in-lined.
For example if I have a complex routine where there are a large number of decisions made within a highly iterative block and those decisions result in similar but slightly differing actions to be carried out. Consider for example, a complex (non DB driven) sort comparer where the sorting algorythm sorts the elements according to a number of different unrelated criteria such as one might do if they were sorting words according to gramatical as well as semantic criteria for a fast language recognition system. I would tend to write helper functions to handle those actions in order to maintain the readability and modularity of the source code.
I know that those helper functions should be in-lined because that is the way that the code would be written if it never had to be understood by a human. I would certainly want to ensure in this case that there were no function calling overhead.
I know this question is about C#. However, you can write inline functions in .NET with F#. see: Use of `inline` in F#
No, there is no such construct in C#, but the .NET JIT compiler could decide to do inline function calls on JIT time. But i actually don't know if it is really doing such optimizations.
(I think it should :-))
In case your assemblies will be ngen-ed, you might want to take a look at TargetedPatchingOptOut. This will help ngen decide whether to inline methods. MSDN reference
It is still only a declarative hint to optimize though, not an imperative command.
Lambda expressions are inline functions! I think, that C# doesn`t have a extra attribute like inline or something like that!

Is there a difference between fun(n::Integer) and fun(n::T) where T<:Integer in performance/code generation?

In Julia, I most often see code written like fun(n::T) where T<:Integer, when the function works for all subtypes of Integer. But sometimes, I also see fun(n::Integer), which some guides claim is equivalent to the above, whereas others say it's less efficient because Julia doesn't specialize on the specific subtype unless the subtype T is explicitly referred to.
The latter form is obviously more convenient, and I'd like to be able to use that if possible, but are the two forms equivalent? If not, what are the practicaly differences between them?
Yes Bogumił Kamiński is correct in his comment: f(n::T) where T<:Integer and f(n::Integer) will behave exactly the same, with the exception the the former method will have the name T already defined in its body. Of course, in the latter case you can just explicitly assign T = typeof(n) and it'll be computed at compile time.
There are a few other cases where using a TypeVar like this is crucially important, though, and it's probably worth calling them out:
f(::Array{T}) where T<:Integer is indeed very different from f(::Array{Integer}). This is the common parametric invariance gotcha (docs and another SO question about it).
f(::Type) will generate just one specialization for all DataTypes. Because types are so important to Julia, the Type type itself is special and allows parameterization like Type{Integer} to allow you to specify just the Integer type. You can use f(::Type{T}) where T<:Integer to require Julia to specialize on the exact type of Type it gets as an argument, allowing Integer or any subtypes thereof.
Both definitions are equivalent. Normally you will use fun(n::Integer) form and apply fun(n::T) where T<:Integer only if you need to use specific type T directly in your code. For example consider the following definitions from Base (all following definitions are also from Base) where it has a natural use:
zero(::Type{T}) where {T<:Number} = convert(T,0)
or
(+)(x::T, y::T) where {T<:BitInteger} = add_int(x, y)
And even if you need type information in many cases it is enough to use typeof function. Again an example definition is:
oftype(x, y) = convert(typeof(x), y)
Even if you are using a parametric type you can often avoid using where clause (which is a bit verbose) like in:
median(r::AbstractRange{<:Real}) = mean(r)
because you do not care about the actual value of the parameter in the body of the function.
Now - if you are Julia user like me - the question is how to convince yourself that this works as expected. There are the following methods:
you can check that one definition overwrites the other in methods table (i.e. after evaluating both definitions only one method is present for this function);
you can check code generated by both functions using #code_typed, #code_warntype, #code_llvm or #code_native etc. and find out that it is the same
finally you can benchmark the code for performance using BenchmarkTools
A nice plot explaining what Julia does with your code is here http://slides.com/valentinchuravy/julia-parallelism#/1/1 (I also recommend the whole presentation to any Julia user - it is excellent). And you can see on it that Julia after lowering AST applies type inference step to specialize function call before LLVM codegen step.
You can hint Julia compiler to avoid specialization. This is done using #nospecialize macro on Julia 0.7 (it is only a hint though).

Custom 'image attribute in Ada?

So I have a thing.
type Thing is new record
...elements...
end record;
I have a function which stringifies it.
function ToString(t: Thing) returns string;
I would like to be able to tell Ada to use this function for Thing'image, so that users of my library don't have to think about whether they're using a builtin type or a Thing.
However, the obvious syntax:
for Thing'image use ToString;
...doesn't work.
Is there a way to do this?
I don’t know why the language doesn’t support this, and I don’t know whether anyone has ever raised a formal proposal that it should (an Ada Issue or AI). The somewhat-related AI12-0020 (the 20th AI for Ada 2012) includes the remark "I don't think we rejected it for technical reasons as much as importance”.
You can see why the Ada Rapporteur Group might think this was relatively unimportant: you can always declare an Image function; the difference between
Pkg.Image (V);
and
Pkg.Typ’Image (V);
isn’t very large.
One common method is to create a unary + function...
function "+"(item : myType) return String;
which is syntactically very light.
Obvious disclaimer: may lead to some ambiguity when applied to numeric types (e.g. Put (+4);)
However there is still the distinction between prebuilt types and user defined types.
'img wouldn't be able to be used by your client's code though, unless you specified an interface that enforced this function to be present (what if the client called on 'img for a private type that didn't have a 'img function defined?).
If you end up having to have an interface, it really doesn't matter what the function is called.

Using a for loop as a condition in an if statement

Is there a way to use a for loop as a condition? Something like this?
if((for(int x = 0; x < 5; x++){if(x == 2){return true;}return false;}) == true)
Edit:
Another example
if(for(int x = 0; x < 5; x++) == 2)
I just wanted to know if it could be done. I expect that Blagovest Buyukliev and marzapower answers are accurate, based on my question. Thank you SO for you helpful responses.
That wouldn't make much sense, as C-ish loops are just execution control structures. There's no type that you can say loops in general have.
From your examples, what it looks to me like you are asking for is the ability to add simple inline functions without having to actually go somewhere else and write down a full function with its own name and whatnot. These are called lambdas.
If you are using C, I'd suggest just making small functions (perhaps even macros - ick) that build and return the type you want.
If you are using C++ there is some stuff in the standard libary in <algorithm> and <functional> you might be interested in. For your given example, I think find_if() would do what you are looking for. Generally that stuff is more of a PITA to use than it is worth though. You have to create a full-blown predicate object to do it, which is way more code and work than just creating your one-line function would have been in the first place.
Boost adds lambda support to C++, and the next standard is supposed to add it properly to the language.
Most functional languages support lambdas, but they generally don't use C syntax like this.
It will probably depend on the language you are writing your code. Generally the for loops do not return a value, unless you include them within an anonymous function also commonly known as lambda function.
In ruby you could accomplish something like that this way:
res = lambda {|array| for i in array do return true if i == 2 end }.call(0..4)
but in Java you will never be able to do such a thing easily without defining a new method.
Update
Generally speaking procedural methods (like ruby, perl, python, lisp, etc.) will provide you with built-in methods for handling anonymous functions, while other languages like C, C++, Java, etc. do not have these characteristics.
By the way, it should be clear that a for loop is a construct in all the languages and not a function, so it should never return a value (like an integer or a boolean or whatever else) but only handle the flow of the code through the processor. Anonymous functions provide us with the ability of incapsulating simple control codes in an inline function.
No, since they are both statements. You need an expression into the if condition. Furthermore, the return statement returns the function in which it has been used.
Why would you do that anyway?
In most languages, no.
for is a statement, not an operator. Unlike operators, statements do not yield a result and cannot be nested into expressions. The condition of the if statement expects an expression that can be evaluated to a boolean value, not a statement.
In languages like Perl and Python you may want to look at the map operator.
This is not good style. Split it up. If you are trying for one-liners Java is the wrong language my friend.

Resources