Bindings for functions with options parameter - reason

It is common practice in JavaScript to have a function that takes in an options parameter, like so:
function foo({ bar1, bar2, bar3 }) {}
foo({ bar1: 5, bar2: 3 })
In Reason/OCaml, one would prefer to use labelled arguments for these functions:
let foo = (~bar1, ~bar2, ~bar) => {}
foo(~bar1=5, ~bar2=3, ())
Now, I know there is this way of creating Reason/Bucklescript bindings for functions like these:
type barObj;
[#bs.obj] external makeBarObj : (
~bar1: int=?,
~bar2: int=?,
~bar3: int=?,
unit
) => barObj = "";
external foo : barObj => t = "foo";
foo(makeBarObj(~bar1=5, ~bar2=3, ());
Is there, however, a simpler way of writing bindings for such functions? My problem with this approach is that it gets quite "long" when calling a function that takes in an options object, especially if it is a polymorphic argument, e.g.:
foo(`BarObj(makebarObj(~bar1=5, ~bar2=3, ())));

You can construct the object directly instead of using a separate function:
[#bs.val] external foo : Js.t({..}) => t = "";
let foo = (~bar1=?, ~bar2=?, ~bar3=?, unit) =>
foo({
"bar1": Js.Nullable.from_opt(bar1),
"bar2": Js.Nullable.from_opt(bar2),
"bar3": Js.Nullable.from_opt(bar3)
});
Which can be called with just
foo(~bar1=5, ~bar2=3, ());
But beware that this isn't exactly equivalent to what [#bs.obj] produces since properties being undefined are not always interpreted as not being defined.
If you need to pass it wrapped in a variant, you could have the object construction function wrap it. You can also usually define a set of functions instead:
fooWithString("bar");
fooWithOptions(~bar1=5, ~bar2=3, ());

Another hypothesis seems to be this one:
[#bs.obj]
external makeBarObj : (~bar1: string=?, ~bar2: int=?, ~bar3: string=?, unit) => barObj =
"";
[#bs.val] external foo : barObj => t = "foo";
let foo = (~bar1=?, ~bar2=?, ~bar3=?) => foo(makeBarObj(~bar1?, ~bar2?, ~bar3?, ()));
And then this way, the client of the API can simply call:
foo(~bar1=5, ~bar2=3, ())
It's basically the same thing as the solution presented in the question, but this hides the object conversion code in the library so that the client doesn't need to worry about it.

Related

Writing a function that returns => T

I'm trying to write a simple converter that turns a java.util.Function into a scala.Function1:
def toScalaProducer[T](f: JavaFunction0[T]) : => T = => f()
Here is another variant that works well:
def toScalaFunction[T](f: JavaFunction0[T]) : () => T =
() => f.apply()
The problem is that I want to pass the converted function into an existing Scala API, but that API only accepts arguments of type => T, not of type () => T.
Is there a way to write the toScalaProducer function?
() => T is the type for a function that takes no arguments and returns something of type T
=> T is the type for a value T that is lazily evaluated. For instance:
def myFunc(t: => Int): Unit = {
// Do something with t
}
myFunc(reallyExpensiveFunctionProducingAnInt())
Here, reallyExpensiveFunctionProducingAnInt could take a long time to run, but will only be executed if the value t is used in myFunc. If you just use type Int instead of => Int it will have been called before myFunc is entered.
Have a look here for more information: Scala's lazy arguments: How do they work?
So if your toScalaProducer function simply executed the Java function and had a return value of T, it should work fine with the API. It will only be executed when needed, so in many ways will behave like passing a function.

How do I use parameter overloading or optional parameters in rust?

I am trying to write a print function for a binary tree and here is what I have so far:
impl TreeNode {
fn print(&self) {
self.print(0);
}
fn print(&self, level: u8) {
for _i in range(0,level) {
print!("\t");
}
match self.data {
Some(x) => println!("{}",x),
None => ()
};
match self.left {
Some(ref x) => x.print(level+1),
None => ()
};
match self.right {
Some(ref x) => x.print(level+1),
None => ()
};
}
}
I am getting the error: duplicate definition of value print. So I was wondering if there is a way to create functions with the same name but different arguments. Alternatively optional parameters would solve this problem, but I don't think that is possible at the moment (at least I couldn't find it via a Google search).
So, what is the best way to do this? Renaming the second print function works but looks ugly and requires you to remember more than one function name if I want to (for this example) print starting from the middle of the tree.
Rust does not have overloading, so it is impossible to have two functions or methods with the same name and with different sets of parameters.
However, it is sometimes possible to emulate overload with traits. This approach is likely inappropriate for your use case, but you can see how it is done in the standard library, where Path::new() constructor can be called with something resembling a vector of bytes:
Path::new("/a/b/c/d") // argument is &str
Path::new(b"/a/b/c/d") // argument is &[u8]
Path::new(Path::new("/a/b/c/d")) // argument is another Path
This is done via BytesContainer trait, and new() method is defined like this:
fn new<T: BytesContainer>(bytes: T) -> Path { ... }
Then this trait is implemented for all the types you want:
impl<'a> BytesContainer for &'a str { ... }
impl<'a> BytesContainer for &'a [u8] { ... }
impl BytesContainer for Path { ... }
// and more
This resembles overloading precisely because new() does exactly the same thing regardless of what kind of input it is provided; it is just a convenience thing which makes Path constructor more flexible. In the end new() just converts its argument to a byte slice. However, this does not allow you to have completely different functions with the same name.

Scala map cannot resolve mapper function

Scala noob here.
I'm trying to apply a map in a class method:
class Miner(args: Args) extends Job(args) {
def fetchUrl(url:String) = {
...
}
TextLine(args("input")).map(url: String => fetchUrl(url))
.write(args("output"))
}
this codes breaks complaining about not being able to resolve the symbol fetchUrl.
I've thought that, fetchUrl being a one argument function, I could just omit the argument and do something like:
TextLine(args("input")).map(fetchUrl)
.write(args("output"))
This now breaks saying that I'm missing arguments for the method fetchUrl.
What gives?
Isn't mapTo a curried function?
I imagine you use this function from this object: (google redirects me to that)
mapTo[U](out: Fields)(mf: (String) ⇒ U)(implicit flowDef: FlowDef, mode: Mode, setter: TupleSetter[U]): Pipe
Perhaps you would use it like this: Textline.mapTo(args("input"))(fetchUrl)
You have some examples of mapTo usage at this page, but based on the Pipe object:
https://github.com/twitter/scalding/wiki/Fields-based-API-Reference#map-functions
Excerpt:
val savings =
items.mapTo(('price, 'discountedPrice) -> 'savings) {
x : (Float, Float) =>
val (price, discountedPrice) = x
price - discountedPrice
}
So not based on TextLine in this example, but also curried...this might be a good hint for you.

How can I use CoffeeScript's "do" with properties of "this"?

CoffeeScript has the handy do statement to preserve variables in a closure. But how do I preserve properties of this with do? That always seems to fail.
Example: in a class method I want to attach an event handler to an HTML element using jQuery. The handler should call another method of the same class with a parameter. Now if I write:
foo = getBar()
$('div').click -> #handler foo
this will obviously not work, because the function will be executed in a different context that doesn't have a method named handler. However, if I use do and I write this:
foo = getBar()
do (#handler, foo) ->
$('div').click -> #handler foo
that will also fail, since #handler translates to this.handler which does not make it through the closure. What's an elegant way to solve this?
Try using a fat arrow (equals sign)
foo = getBar()
$('div').click => #handler foo
Or, get a reference to handler before your callback.
cbHandler = #handler
foo = getBar()
$('div').click -> cbHandler foo

Design-by-contract support in coffeescript without language extensions

I consider design-by-contract an useful technique and want to apply it to my coffeescript code.
There is contracts.coffee, which looks really nice (like Haskell):
id :: (Num) -> Num
id = (x) -> x
Downside is that it is a language extension. I'm hesitating because I'm afraid to trade in trouble with tool support. (Am I too conservative?)
Though it really looks great, I would prefer a library solution at the moment. For Ruby, I recently found contracts.ruby, which shares the same elegance but has the advantage that it is just plain Ruby:
require 'contracts'
include Contracts
Contract Num => Num
def id(x) ; x ; end
Is there something similiar for coffeescript?
I read about jsContracts but haven't tested it. Seems to be a useful library, but it lacks the elegance of the Ruby DSL or the contracts.coffee language extension.
Questions:
Is there a syntactically nice design-by-contract library for coffeescript (or Javascript) that integrates seamlessly into the common toolchains?
Are my concerns about contracts.coffee justified? (If not, it seems to be the perfect fit.)
See this question: Is there a code contract library for JavaScript?
You can use https://npmjs.org/package/contracts-js, which is the sort of backend, if you will, to contracts.coffee. The downside is that it requires proxies, which are not supported very well in front-end JavaScript.
Seems like an interesting idea for a different kind of library, maybe one that extends functions with contracts...
Its extremely easy to define your own DSL within CoffeeScript. If you want to create a type checking framework you could for example create a class like this
class A
#def foo:
params: [isNum, isBool,isNotNull]
body: (x, y, z) -> console.log "foo: #{x}, #{y}, #{z}"
#def should create a method named "foo" and check its parameters according to their position by calling the functions given in the "params" array.
Lets write some test first
a = new A()
a.foo 3, true, "foo"
a.foo "string", true, "foo"
a.foo 3, "string", "foo"
a.foo 3, false, null
Then we need some helper methods that will do the actual parameter checking
isNum = (p)-> console.log "p isnt a number its => #{p}" if typeof p != "number"
isBool = (p)-> console.log "p isnt a bool its => #{p}" if typeof p != "boolean"
isNotNull = (p)-> console.log "p is null" if p == null or p == undefined
Probably they should do something more useful (like throwing an exception). For our example they should be sufficient.
Now our class A calls a class-method which is not yet defined. We will create a base class for this and the inherit our class A from it
class ContractBase
#def: (fndef)->
#get the name of the "function definition" object
#should be the only key
name = Object.keys(fndef)[0]
#get the real function body
fn = fndef[name]["body"]
#get the params
params = fndef[name]["params"]
# create a closure and assign it to the prototype
#::[name] = ->
#check the parameters first
for value, index in arguments
#get the check at the index of the argument
check = params[index]
#and run it if available
check(value) if check
#call the real function body
fn arguments...
#and finally change A to extend from ContractBase
class A extends ContractBase
...
Obviously there are a few warts in it
The arguments array and the parameter array can be of different lenght (there is no check for that yet)
The helper functions should throw an exception
the helper functions should be combinable like isNotNull(isNum)
you are circumventing the "normal" way of defining a method so your resulting javascript code will be harder to read and to debug - maybe not
Here is the full running code in one go
class ContractBase
#def: (fndef)->
name = Object.keys(fndef)[0]
fn = fndef[name]["body"]
params = fndef[name]["params"]
#::[name] = ->
for value, index in arguments
check = params[index]
check(value) if check
fn arguments...
isNum = (p)-> console.log "p isnt a number its => #{p}" if typeof p != "number"
isBool = (p)-> console.log "p isnt a bool its => #{p}" if typeof p != "boolean"
isNotNull = (p)-> console.log "p is null" if p == null or p == undefined
class A extends ContractBase
#def foo:
params: [isNum, isBool,isNotNull]
body: (x, y, z) -> console.log "foo: #{x}, #{y}, #{z}"
a = new A()
a.foo 3, true, "foo"
a.foo "string", true, "foo"
a.foo 3, "string", "foo"
a.foo 3, false, null
Its roughly 1/3 of the length of the corresponding Javascript code and certainly much more readable as it communicates intent much better (imo)