Which programming languages allow default values for method parameters? - programming-languages

I'm curious which languages allow you to do something like this:
method foo(String bar = "beh"){
}
If you call foo like this:
foo();
bar will be set to "beh", but if you call like this:
foo("baz");
bar will be set to "baz".

almost all Lisps
Ruby
Python
C++
C#
Visual Basic.NET
Tcl
Visual Basic
Ioke
Seph
Cobra
Nemerle
Mirah
Delphi
Groovy
PHP
Fancy
Scala

PHP:
function foo($var = "foo") {
print $var;
}
foo(); // outputs "foo"
foo("bar"); // outputs "bar"
Python:
def myFun(var = "foo"):
print var
Ruby:
def foo(var="foo")
print var
end
Groovy:
def foo(var="foo") {
print var
}

Ones I can think of
C# 4.0
C++
VB.Net (all versions)
VB6
F# (members only)
Powershell
IDL
Ruby

Racket provides this, as well as keyword arguments:
(define (f x [y 0]) (+ x y))
(f 1) ; => 1
(f 10 20) ; => 30
(define (g x #:y [y 0]) (- x y))
(g 1) ; => 1
(g 10 #:y 20) ; => -10
They're described in the documentation.

Delphi has allowed this since about version 5 - released in 1999
procedure foo(const bar: string = 'beh');
begin
...
end;
foo;
foo('baz');

Perl does with Method::Signatures.

Python:
def foo(bar = value):
# This function can be invoked as foo() or foo(something).
# In the former case, bar will have its default value.
pass

as of c# 4.0 you can now have default params. Finally!
Also C++, Ruby and VB

TCL provides this functionality
proc procName {{arg1 defaultValue} {arg2 anotherDefaultValue}} {
# proc body
}

D:
void foo(int x, int y = 3)
{
...
}
...
foo(4); // same as foo(4, 3);
Fantom:
class Person
{
Int yearsToRetirement(Int retire := 65) { return retire - age }
Int age
}

Java has a workaround.
You can have the foo method with no parameters that calls the foo method with parameters setting the default value, like this:
void foo() {
foo("beh");
}
void foo(String bar) {
this.bar = bar;
}

Add to the list Realbasic (indeed Realbasic has almost every nice feature of every language I can think of, including introspection and sandboxed scripting).
Python. (But watch out for mutables per http://effbot.org/zone/default-values.htm )
And plenty of languages, including C, allow variable numbers of parameters which effectively lets you do the same thing.
In many modern scripting languages, including PHP, JavaScript, and Perl, a better idiom for handling such things is to allow an associative array or object as a parameter, and then assign defaults if needed.
e.g.
function foo( options ){
if( options.something === undefined ){
options.something = some_default_value;
}
...
}
This eliminates the necessity of putting the defaultable values at the end of the list of parameters and remembering all the stuff you don't want to override.
As always -- use in moderation.

You can do it in PL/SQL.

I know Python allows this, while C,C++ don't.

Related

How to mark non-pure function as pure in Nim

Is there a way to mark non-pure function p as pure? Maybe with some pragma?
I'm using p for debug, and it can't be used inside pure func procs.
playground
proc p(message: string): void = echo message
func purefn: void =
p "track"
purefn()
Error:
/usercode/in.nim(3, 6) Error: 'purefn' can have side effects
Well, for a start you can just use debugEcho instead of echo - it has no side effects (and it's specifically made for use-cases like that).
In other cases you can "lie" to the compiler by doing:
proc p(message: string) =
{.cast(noSideEffect).}:
echo message
func purefn =
p "track"
purefn()
as described in https://nim-lang.org/docs/manual.html#pragmas-nosideeffect-pragma, but I would advise against it.
For your case, you can use debugEcho inside of echo which fakes having no side effects.
Other than that, you can use the {.cast(noSideEffect).} pragma if you're not using echo in your real code:
proc p(message: string): void = echo message
func purefn: void =
{.cast(noSideEffect).}:
p "track"
purefn()

Make msvc C4706 go away without pragmas

Following code in MSVC generates warning about assignment in conditional expression.
https://godbolt.org/z/i_rwY9
int main()
{
int a;
if ((a = 5)) {
return 1;
}
return a;
}
Note that I tried to use the double () around if since that makes the warning go away with g++, but I do not know how to make it go away in msvc without extracting the assignment from condition.
Is there a way to nudge msvc to figure out that this assignment is intentional?
I know I can use pragmas to disable this warning, but pattern is very common so I would like to get a solution without pragmas if one exists.
The MSVC compiler will give this warning unless you can convince it that you really do know what you're doing. Adding at least one 'real' logical test will achieve this:
int main()
{
int a;
if ((a = 5) != 0) {
return 1;
}
return a;
}
Note that the constant 5 can readily be replaced with any variable or valid expression: adding the explicit != 0 test does nothing to actually change the outcome of the code (and it is unlikely to change the generated assembly).

Function Overloading in golang [duplicate]

I'm porting a C library to Go. A C function (with varargs) is defined like this:
curl_easy_setopt(CURL *curl, CURLoption option, ...);
So I created wrapper C functions:
curl_wrapper_easy_setopt_str(CURL *curl, CURLoption option, char* param);
curl_wrapper_easy_setopt_long(CURL *curl, CURLoption option, long param);
If I define function in Go like this:
func (e *Easy)SetOption(option Option, param string) {
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(param)))
}
func (e *Easy)SetOption(option Option, param long) {
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(param)))
}
The Go compiler complains:
*Easy·SetOption redeclared in this block
So does Go support function (method) overloading, or does this error mean something else?
No it does not.
See the Go Language FAQ, and specifically the section on overloading.
Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.
Update: 2016-04-07
While Go still does not have overloaded functions (and probably never will), the most useful feature of overloading, that of calling a function with optional arguments and inferring defaults for those omitted can be simulated using a variadic function, which has since been added. But this comes at the loss of type checking.
For example: http://changelog.ca/log/2015/01/30/golang
According to this, it doesn't: http://golang.org/doc/go_for_cpp_programmers.html
In the Conceptual Differences section, it says:
Go does not support function overloading and does not support user defined operators.
Even though this question is really old, what I still want to say is that there is a way to acheive something close to overloading functions. Although it may not make the code so easy to read.
Say if you want to overload the funtion Test():
func Test(a int) {
println(a);
}
func Test(a int, b string) {
println(a);
println(b);
}
The code above will cause error. However if you redefine the first Test() to Test1() and the second to Test2(), and define a new function Test() using go's ..., you would be able to call the function Test() the way it is overloaded.
code:
package main;
func Test1(a int) {
println(a);
}
func Test2(a int, b string) {
println(a);
println(b);
}
func Test(a int, bs ...string) {
if len(bs) == 0 {
Test1(a);
} else {
Test2(a, bs[0]);
}
}
func main() {
Test(1);
Test(1, "aaa");
}
output:
1
1
aaa
see more at: https://golangbyexample.com/function-method-overloading-golang/ (I'm not the author of this linked article but personally consider it useful)
No, Go doesn't have overloading.
Overloading adds compiler complexity and will likely never be added.
As Lawrence Dol mentioned, you could use a variadic function at the cost of no type checking.
Your best bet is to use generics and type constraints that were added in Go 1.18
To answer VityaSchel's question, in the comments of Lawrence's answer, of how to make a generic sum function, I've written one below.
https://go.dev/play/p/hRhInhsAJFT
package main
import "fmt"
type Number interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}
func Sum[number Number](a number, b number) number {
return a + b
}
func main() {
var a float64 = 5.1
var b float64 = 3.2
println(Sum(a, b))
var a2 int = 5
var b2 int = 3
println(Sum(a2, b2))
}

Conventions to specifying digital fixed point binary numbers with macros

I was wondering if there an established convention to specifying fixed point binary numbers in decimal format (with the use of a macro). I am not sure if this possible in C/C++, but perhaps this is implemented in some language(s) and there is a notational standard like 0x000000,1.2f,1.2d,1l,etc
Take this example for instance:
I am using Q15.16 for instance, but would like to have the convenience of specifying numbers in decimal format, perhaps something like this:
var num:Int32=1.2fp;
Presumably, the easiest way with regards to Haxe macros, numbers can be initialized with a function:
#:macro
fp_from_float(1.2);
But it would be nice to have a shorthand notation.
Have you seen Luca's Fixed Point example with Haxe 3 and Abstracts?
It's here:
https://groups.google.com/forum/?fromgroups=#!topic/haxelang/JsiWvl-c0v4
Summing it up, with the new Haxe 3 abstract types, you can define a type that will be compiled as an Int:
abstract Fixed16(Int)
{
inline function new(x:Int) this = x;
}
You can also define "conversion functions", which will allow you to automatically convert a float into Fixed16:
#:from public static inline function fromf(x:Float) {
#if debug
if (x >= 32768.0 || x < -32768.0) throw "Conversion to Fixed16 will overflow";
#end
return new Fixed16(Std.int(x*65536.0));
}
The secret here is the #:from metadata. With this code, you will already be able to declare fixed types like this:
var x:Fixed16 = 1.2;
Luca's already defined some operators, to make working with them easier, like:
#:op(A+B) public inline static function add(f:Fixed16, g:Fixed16) {
#if debug
var fr:Float = f.raw();
var gr:Float = g.raw();
if (fr+gr >= 2147483648.0 || fr+gr < -2147483648.0) throw "Addition of Fixed16 values will overflow";
#end
return new Fixed16(f.raw()+g.raw());
}
Again, the secret here is in #:op(A+B) metadata, which will annotate that this function may be called when handling addition. The complete GIST code is available at https://gist.github.com/deltaluca/5413225 , and you can learn more about abstracts at http://haxe.org/manual/abstracts

Any programming language with "strange" function call?

I was wondering, is there any programming language where you can have function calls like this:
function_name(parameter1)function_name_continued(parameter2);
or
function_name(param1)function_continued(param2)...function_continued(paramN);
For example you could have this function call:
int dist = distanceFrom(cityA)to(cityB);
if you have defined distanceFromto function like this:
int distanceFrom(city A)to(city B)
{
// find distance between city A and city B
// ...
return distance;
}
As far as I know, in C, Java and SML programming languages, this cannot be done.
Are you aware of any programming language that let's you define and call
functions in this way?
It looks an awful lot like Objective-C
- (int)distanceFrom:(City *)cityA to:(City *)cityB {
// woah!
}
Sounds a lot like Smalltalk's syntax, (which would explain Objective-C's syntax - see kubi's answer).
Example:
dist := metric distanceFrom: cityA to: cityB
where #distanceFrom:to: is a method on some object called metric.
So you have "function calls" (they're really message sends) like
'hello world' indexOf: $o startingAt: 6. "$o means 'the character literal o"
EDIT: I'd said "Really, #distanceFrom:to: should be called #distanceTo: on a City class, but anyway." Justice points out that this couples a City to a Metric, which is Bad. There are good reasons why you might want to vary the metric - aeroplanes might use a geodesic while cars might use a shortest path based on the road network.)
For the curious, Agda2 has a similar, very permissive syntax. The following is valid code:
data City : Set where
London : City
Paris : City
data Distance : Set where
_km : ℕ → Distance
from_to_ : City → City → Distance
from London to London = 0 km
from London to Paris = 342 km
from Paris to London = 342 km
from Paris to Paris = 0 km
If
from Paris to London
is evaluated, the result is
342 km
Looks a lot like a fluent interface or method chaining to me.
In Python, you can explicitly pass the name of the arguments you're calling the function with, which lets you pass them in a different order or skip optional arguments:
>>> l = [3,5,1,2,4]
>>> print l.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
>>> l.sort (reverse=True)
>>> l
[5, 4, 3, 2, 1]
This looks a lot like what the Objective C syntax is doing, tagging each argument to a function with its name.
C# 4.0's Named and Optional Arguments feature allows you to achieve something pretty similar:
public static int Distance(string from, string to, string via = "")
{
...
}
public static void Main()
{
int distance;
distance = Distance(from: "New York", to: "Tokyo");
distance = Distance(to: "Tokyo", from: "New York");
distance = Distance(from: "New York", via: "Athens", to: "Tokyo");
}
(see my very favourite personal effort - the final C++ approach at the end of this answer)
Language One
Objective-C but the calling syntax is [object message] so would look like:
int dist = [cities distanceFrom:cityA to:cityB];
if you have defined distanceFromto function like this, within a cities object:
- (int)distanceFrom:(City *)cityA to:(City *)cityB
{
// find distance between city A and city B
// ...
return distance;
}
Language Two
I also suspect you could achieve something very close to this in the IO Language but I'm only just looking at it. You may also want to read about it in comparison to other languages in Seven Languages in Seven Weeks which has a free excerpt about IO.
Language Three
There's an idiom ("chaining") in C++ where you return temporary objects or the current object that is used to replace keyword arguments, according to The Design and Evolution of C++ and looks like this:
int dist = distanceFrom(cityA).to(cityB);
if you have defined distanceFrom function like this, with a little helper object. Note that inline functions make this kind of thing compile to very efficient code.
class DistanceCalculator
{
public:
DistanceCalculator(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
inline DistanceCalculator distanceFrom(City* from)
{
return DistanceCalculator(from);
}
Duhh, I was in a hurry earlier, realised I can refactor to just use a temporary object to give the same syntax:
class distanceFrom
{
public:
distanceFrom(City* from) : fromCity(from) {}
int to(City * toCity)
{
// find distance between fromCity and toCity
// ...
return distance;
}
private:
City* fromCity;
};
MY FAVOURITE
and here's an even more inspired C++ version that allows you to write
int dist = distanceFrom cityA to cityB;
or even
int dist = distanceFrom cityA to cityB to cityC;
based on a wonderfully C++ ish combination of #define and classes:
#include <vector>
#include <numeric>
class City;
#define distanceFrom DistanceCalculator() <<
#define to <<
class DistanceCalculator
{
public:
operator int()
{
// find distance between chain of cities
return std::accumulate(cities.begin(), cities.end(), 0);
}
DistanceCalculator& operator<<(City* aCity)
{
cities.push_back(aCity);
return *this;
}
private:
std::vector<City*> cities;
};
NOTE this may look like a useless exercise but in some contexts it can be very useful to give people a domain-specific language in C++ which they compile alongside libraries. We used a similar approach with Python for geo-modeling scientists at the CSIRO.
You can do this in C, albeit unsafely:
struct Arg_s
{
int from;
int to;
};
int distance_f(struct Arg_s args)
{
return args.to - args.from;
}
#define distance(...) distance_f( ((struct Arg_s){__VA_ARGS__}) )
#define from_ .from =
#define to_ .to =
uses compound literals and designated initializers.
printf("5 to 7 = %i\n",distance(from_ 5, to_ 7));
// 5 to 7 = 2
3 of the 4 confederated languages from RemObjects in their Elements Compiler have this capability in precisely the OP's requested syntax (to support Objective-C runtime, but made available to all operating systems).
in Hydrogene (an extended C#)
https://docs.elementscompiler.com/Hydrogene/LanguageExtensions/MultiPartMethodNames
in Iodine (an extended Java)
https://docs.elementscompiler.com/Iodine/LanguageExtensions/MultiPartMethodNames
in Oxygene (an extended ObjectPascal), scroll down to Multi-Part Method Names section
https://docs.elementscompiler.com/Oxygene/Members/Methods
This looks similar to function overloading (C++/C#)/default parameters (VB).
Default Parameters allow the person defining the function to set defaults for the latter parameters:
e.g. c# overloading:
int CalculateDistance(city A, city B, city via1, city via2)
{....}
int CalculateDistance(city A, city B)
{
return CalculateDistance(city A, city B, null, null)
}
You can use a member function for this.
cityA.distance_to(cityB);
That's valid code in C++, C(with a little tweaking), C#, Java. Using method chains, you can do:
cityA.something(cityB).something(cityC).something(cityD).something(cityE);
In SML you could simply make "to" some value (unit, for example), and "distanceFrom" a curried function that takes three parameters. For example:
val to = ()
fun distanceFrom x _ y = (* implementation function body *)
val foo = distanceFrom cityA to cityB
You could also take advantage of the fact that SML doesn't enforce naming conventions on datataype constructors (much to many peoples' annoyance), so if you want to make sure that the type system enforces your custom syntax:
datatype comp = to
fun distanceFrom x to y = (* implementation *)
val foo = distanceFrom cityA to cityB (* works *)
val foo' = distanceFrom cityA cityB (* whoops, forgot 'to' - type error! *)
You could do this in Scheme or LISP using macros.
The form will be something like:
(DISTANCE-FROM city-a TO city-b)
The symbols in uppercase denotes syntax.
You could even do something like 'named parameters':
(DISTANCE TO city-a FROM city-b)
(DISTANCE FROM city-a TO city-b)
Tcl allows you to do something like this:
proc distance {from cityA to cityB} {...}
set distance [distance from "Chicago IL" to "Tulsa OK"]
I'm not sure if that's quite what you are thinking of though.
You can do it in Java, Use Builder pattern that appears in the book Effective Java by Joshua Bosch (this is second time I put this link in SO, I still didn't use that patern, but looks great)
Well, in Felix you can implement this in two steps: first, you write an ordinary function. Then, you can extend the grammar and map some of the new non-terminals to the function.
This is a bit heavyweight compared to what you might want (welcome to help make it easier!!) I think this does what you want and a whole lot more!
I will give a real example because the whole of the Felix language is actually defined by this technique (below x is the non-terminal for expressions, the p in x[p] is a precedence code):
// alternate conditional
x[sdollar_apply_pri] := x[stuple_pri] "unless" x[let_pri]
"then" x[sdollar_apply_pri] =>#
"`(ast_cond ,_sr ((ast_apply ,_sr (lnot ,_3)) ,_1 ,_5))";
Here's a bit more:
// indexes and slices
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'subscript) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'substring) (,_1 ,_4 ,_6)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" sexpr "to" "]" =>#
"`(ast_apply ,_sr (,(noi 'copyfrom) (,_1 ,_4)))";
x[sfactor_pri] := x[sfactor_pri] "." "[" "to" sexpr "]" =>#
"`(ast_apply ,_sr (,(noi 'copyto) (,_1 ,_5)))";
The Felix grammar is ordinary user code. In the examples the grammar actions are written in Scheme. The grammar is GLR. It allows "context sensitive keywords", that is, identifiers that are keywords in certain contexts only, which makes it easy to invent new constructs without worrying about breaking existing code.
Perhaps you would like to examine Felix Grammar Online.

Resources