functions with named parameters and default values

38 views
Skip to first unread message

Răzvan Rotaru

unread,
Jan 6, 2015, 9:55:04 AM1/6/15
to yeti...@googlegroups.com
Hi,

I'm trying to find a way to have named parameters in functions. Intuitively, structures with destructuring bind can be used for that:

> myfunction {a, b, c} = println (a+b+c)
myfunction
is {
   
.a is number,
   
.b is number,
   
.c is number
} -> () = <code$myfunction>
> myfunction {a=100, b=50, c=99}
249

Can I somehow specify default values for parameters?

Cheers,
Razvan

chrisichris

unread,
Jan 6, 2015, 5:43:40 PM1/6/15
to yeti...@googlegroups.com
Hi, 

you can use a list of variants:

myFn params = 
  (var a = 100; 
  var b = 50;
  var c = 10;
  for params \case of
     A n: a := n;
     B n: b := n;
     C n: c := n;
  esac;
  println (a + b + c));

myFn [A 20, C 10];


Another thing you could do especially when there are many options is define a default structure

> defS = {a = 10, b = 20, c = 30}

> mFn {a,b,c} = println (a + b + c)

> mFn (do x: x with {a = 100} done defS)

the last call looks a bit strange but the with in a funciton makes sure that you only override fields which are in the struct

Răzvan Rotaru

unread,
Jan 7, 2015, 4:56:46 AM1/7/15
to yeti...@googlegroups.com
Thanks,

The first option would work, even though it's not as nice as destructuring bind with structures (and it requires more typing). The second option puts the burden in the hands of the caller, which not something I would like to do.

Cheers,
Răzvan

Răzvan Rotaru

unread,
Jan 13, 2015, 7:44:57 AM1/13/15
to yeti...@googlegroups.com
Would it be possible/difficult to add default values to structures?

Răzvan

Madis

unread,
Jan 13, 2015, 12:50:34 PM1/13/15
to yeti...@googlegroups.com

On Tue, 13 Jan 2015, Răzvan Rotaru wrote:

> Would it be possible/difficult to add default values to structures?

Possible yes, I considered it at some time, but imho variant lists do the
same job in more flexible way - for example you can construct the optional
parameter list dynamically at runtime. Yes it's a bit more work inside the
function, but then it would be more useful to add mechanism for doing that
parameter extraction in less code. In the end, it would be more useful to
add some kind of compile-time macros to the language, but that's probably
not going to happen now.

Răzvan Rotaru

unread,
Jan 13, 2015, 2:21:29 PM1/13/15
to yeti...@googlegroups.com, ma...@cyber.ee
My main worry with variant lists is that you have to process them sequentially, i.e. I can't have direct access to the value of one parameter. And this processing requires state.

Razvan
Reply all
Reply to author
Forward
0 new messages