Design-by-contract support in coffeescript without language extensions - coffeescript

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)

Related

Bindings for functions with options parameter

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.

How to use fresh identifier in function parameter list in Scala macro

In an effort to learn Scala's macro system, I thought I'd try my hand at writing a basic CPS transformation macro. I've already written a fairly comprehensive CPS transformation framework for Clojure, so I'm pretty familiar with the CPS transform itself. However, I'm getting stuck transforming function / method applications.
For the CPS transform, function calls of the following form:
cps(f(<a>, <b>, <c>, ...))
need to be translated into an expression of the form:
cps(<a>){ $a =>
cps(<b>){ $b =>
cps(<c>){ $c =>
... => f($a, $b, $c, ...)
}
}
}
Obviously, the parameters of the generated continuation lambdas (e.g., $a) need to be fresh symbols so they can't inadvertently conflict with variable names in the lexical context. So for each argument arg, I generate a fresh name:
val name = Ident(TermName(c.freshName))
(where c is the macro's Context) which I then use in the following quasiquote:
q"""cps(arg)($name => $remainder)"""
where remainder refers to the remainder of the computation.
The macro itself compiles fine, but when I try to use it with an expression that involves a function application, I get the following error:
... exception during macro expansion:
[error] java.lang.IllegalArgumentException: fresh$macro$1 is not valid representation of a parameter, consider reformatting it into q"val $name: $T = $default" shape
However, I don't think it's possible to perform the recommended "reformatting", since there is no $default to provide.
Here's a minimal example that illustrates the issue I'm having:
def id[A](expr : A) : A = macro idImpl[A]
def idImpl[A](c : blackbox.Context)(expr : c.Expr[A]) : c.Expr[A] = {
import c.universe._
val name = Ident(TermName(c.freshName))
//c.Expr(q"""val $name = $expr; $name""")
c.Expr(q"""($name => $name)($expr)""")
}
Note that it works if you replace the lambda expression with the commented line.
So my question: How can a name generated by freshName be used as the parameter name for an anonymous function?
I believe you need a ValDef of the form val $name: $T = _, where the _ is represented by NoTree. Initializing variables with _ is valid Scala, setting references to null and numbers to 0 (i.e. the default values), but is also used as an internal placeholder when there are ValDefs (e.g. function parameters) but no sane default.
I’m on mobile here, so I can’t test it. In any case, you can destructure the value q"a: Any => a" in the REPL to find what the compiler normally sets as the default, if NoTree doesn't work.

Equality of functions in Scala, is functions objects in Scala?

I am reading the book Programming in Scala. In the book, it says that "A function literal is compiled into a class that when instantiated at runtime is a function value". And it mentions that "Function values are objects, so you can store them in variables if you like".
So I try to check the equality between functions. But I failed.
If function is object in Scala, then it should behave like other objects in Scala. Maybe check equality of function is meaningless, so it is disabled?
And will function be compiled into object in Scala?
Lambda are compiled as anonymous classes (not case class, as far as I remember). That means if you do:
val f1: (String) => String = _ => "F1"
val f2: (String) => String = _ => "F2"
Both f1 and f2 are subtype of Function1[String,String], but they are of different anonymous classes, so can't equal.
If you write it as:
case class F(res: String) extends ((String) => String) {
def apply(s: String) = res
}
Then:
val f1: (String) => String = F("A")
val f2: (String) => String = F("A")
f1 == f2 // true
It's not clear what "equality" of functions means. Typically, what people care about is "do these two functions compute the same result?"
This, however, is a well-known undecidable problem, the Function Problem. The actual proof is more complex, obviously, but a simple intuition is: if you could tell whether two functions were equal, then you could solve the Halting Problem by asking "is this function equal to while (true) {}?"
So, we cannot decide whether two functions compute the same result. What we could do, is for example, check whether they contain the exact same code. But that is pretty boring. Just some tiny compiler optimization or renaming a single variable will make two functions that intuitively should be equal not equal.
Ergo, we take the easy way out: two functions are equal if they are identical, otherwise they aren't.

How to track nested functions in Scala

I'd like to have some basic knowledge of how deeply my function call is nested. Consider the following:
scala> def decorate(f: => Unit) : Unit = { println("I am decorated") ; f }
decorate: (f: => Unit)Unit
scala> decorate { println("foo") }
I am decorated
foo
scala> decorate { decorate { println("foo") } }
I am decorated
I am decorated
foo
For the last call, I'd like to be able to get the following:
I am decorated 2x
I am decorated 1x
foo
The idea is that the decorate function knows how deeply its nested. Ideas?
Update: As Nikita had thought, my example doesn't represent what I'm really after. The goal is not to produce the strings so much as to be able to pass some state through a series of calls to the same nested function. I think Régis Jean-Gilles is pointing me in the right direction.
You can use the dynamic scope pattern. More prosaically this means using a thread local variable (scala's DynamicVariable is done just for that) to store the current nesting level. See my answer to this other question for a partical example of this pattern: How to define a function that takes a function literal (with an implicit parameter) as an argument?
This is suitable only if you want to know the nesting level for a very specific method though. If you want a generic mecanism that works for any method then this won't work (as you'd need a distinct variable for each method). In this case the only alternative I can think of is to inspect the stack, but not only is it not very reliable, it is also extremely slow.
UPDATE: actually, there is a way to apply the dynamic scope pattern in a generic way (for any possible method). The important part is to be able to implicitly get a unique id for each method. from there, it is just a matter of using this id as a key to associate a DynamicVariable to the method:
import scala.util.DynamicVariable
object FunctionNestingHelper {
private type FunctionId = Class[_]
private def getFunctionId( f: Function1[_,_] ): FunctionId = {
f.getClass // That's it! Beware, implementation dependant.
}
private val currentNestings = new DynamicVariable( Map.empty[FunctionId, Int] )
def withFunctionNesting[T]( body: Int => T ): T = {
val id = getFunctionId( body )
val oldNestings = currentNestings.value
val oldNesting = oldNestings.getOrElse( id, 0 )
val newNesting = oldNesting + 1
currentNestings.withValue( oldNestings + ( id -> newNesting) ) {
body( newNesting )
}
}
}
Usage:
import FunctionNestingHelper._
def decorate(f: => Unit) = withFunctionNesting { nesting: Int =>
println("I am decorated " + nesting + "x") ; f
}
To get a unique id for the method, I actually get an id for a the closure passed to withFunctionNesting (which you must call in the method where you need to retrieve the current nesting). And that's where I err on the implementation dependant side: the id is just the class of the function instance. This does work as expected as of now (because every unary function literal is implemented as exactly one class implementing Function1 so the class acts as a unique id), but the reality is that it might well break (although unlikely) in a future version of scala. So use it at your own risk.
Finally, I suggest that you first evaluate seriously if Nikita Volkov's suggestion of going more functional would not be a better solution overall.
You could return a number from the function and count how many levels you are in on the way back up the stack. But there is no easy way to count on the way down like you have given example output for.
Since your question is tagged with "functional programming" following are functional solutions. Sure the program logic changes completely, but then your example code was imperative.
The basic principle of functional programming is that there is no state. What you're used to have as a shared state in imperative programming with all the headache involved (multithreading issues and etc.) - it is all achieved by passing immutable data as arguments in functional programming.
So, assuming the "state" data you wanted to pass was the current cycle number, here's how you'd implement a function using recursion:
def decorated ( a : String, cycle : Int ) : String
= if( cycle <= 0 ) a
else "I am decorated " + cycle + "x\n" + decorated(a, cycle - 1)
println(decorated("foo", 3))
Alternatively you could make your worker function non-recursive and "fold" it:
def decorated ( a : String, times : Int )
= "I am decorated " + times + "x\n" + a
println( (1 to 3).foldLeft("foo")(decorated) )
Both codes above will produce the following output:
I am decorated 3x
I am decorated 2x
I am decorated 1x
foo

About Scala's assignments and setter methods

Edit: The bug which prompted this question has now been fixed.
In the Scala Reference, I can read (p. 86):
The interpretation of an assignment to
a simple variable x = e depends on the
definition of x. If x denotes a
mutable variable, then the assignment
changes the current value of x to be
the result of evaluating the
expression e. The type of e is
expected to conform to the type of x.
If x is a parameterless function
defined in some template, and the same
template contains a setter function
x_= as member, then the assignment x =
e is interpreted as the invocation
x_=(e) of that setter function.
Analogously, an assignment f .x = e to
a parameterless function x is
interpreted as the invocation f.x_=(e).
So, for instance, something like this works fine:
class A {
private var _a = 0
def a = _a
def a_=(a: Int) = _a = a
}
I can then write
val a = new A
a.a = 10
But if I define the class like this, adding a type parameter to method a:
class A {
private var _a = 0
def a[T] = _a
def a_=(a: Int) = _a = a
}
then it doesn't work any more; I get an error: reassignment to val if I write a.a = 10. Funny enough, it still works with no type parameter and an implicit parameter list, for instance.
Arguably, in this example, the type parameter is not very useful, but in the design of DSLs, it would be great to have the setter method called even if the getter has type parameters (and by the way, adding type parameters on the setter is allowed and works fine).
So I have three questions:
Is there a workaround?
Should the current behavior be considered a bug?
Why does the compiler enforce a getter method to allow using the syntactic sugar for the setter?
UPDATE
Here's what I'm really trying to do. It's rather long, sorry, I meant to avoid it but I realized it was more confusing to omit it.
I'm designing GUIs with SWT in Scala, and having huge fun using Dave Orme's XScalaWT, which immensely reduces the amount of needed code. Here's an example from his blog post on how to create an SWT Composite that converts °C to °F degrees:
var fahrenheit: Text = null
var celsius: Text = null
composite(
_.setLayout(new GridLayout(2, true)),
label("Fahrenheit"),
label("Celsius"),
text(fahrenheit = _),
text(celsius = _),
button(
"Fahrenheit => Celsius",
{e : SelectionEvent => celcius.setText((5.0/9.0) * (fahrenheit - 32)) }
),
button(
"Celsius -> Fahrenheit",
{e : SelectionEvent => fahrenheit.setText((9.0/5.0) * celsius + 32) })
)
)
The argument to each of the widget-constructing methods is of type (WidgetType => Any)*, with a few useful implicit conversions, which for instance allow to directly specify a string for widgets that have a setText() method. All constructor functions are imported from a singleton object.
In the end, I'd like to be able to write something along these lines:
val fieldEditable = new WritableValue // observable value
composite(
textField(
editable <=> fieldEditable,
editable = false
),
checkbox(
caption = "Editable",
selection <=> fieldEditable
)
)
This would bind the editable property of the textfield to the selection of the checkbox through the WritableValue variable.
First: named arguments are not applicable here, so the line editable = false has to come from somewhere. So, along the widget-constructing methods in the singleton object, I could write, conceptually,
def editable_=[T <: HasEditable](value: Boolean) = (subject: T) => subject.setEditable(value)
... but this works only if the getter is also present. Great: I'd need the getter anyway in order to implement databinding with <=>. Something like this:
def editable[T <: HasEditable] = new BindingMaker((widget: T) => SWTObservables.observeEditable(widget))
If this worked, life would be good because I can then define <=> in BindingMaker and I can use this nice syntax. But alas, the type parameter on the getter breaks the setter. Hence my original question: why would this simple type parameter affect whether the compiler decides to go ahead with the syntactic sugar for calling the setter?
I hope this makes it a bit clearer now. Thanks for reading…
UPDATE Deleted the entire previous answer in light of new information.
There's a lot of very odd stuff going on here, so I'm going try try and explain my understanding of what you have so far:
def editable_=[T <: HasEditable](value: Boolean) = (subject: T) => subject.setEditable(value)
This is a setter method, and exists purely so that it can give the appearance of beinng a named parameter
in your DSL. It sets nothing and actually returns a Function.
textField(
editable <=> fieldEditable,
editable = false
)
This is calling the textField factory method, with what looks like a named param, but is actually the setter method defined previously.
Amazingly, the approach seems to work, despite my initial concern that the compiler would recognize this as a named parameter and produce a syntax error. I tested it with simple monomorphic (non-generic) methods, though it does require the getter method to be defined for the setter to be seen as such - a fact that you've already noted.
Some amount of "cleverness" is often required in writing a DSL (where it would otherwise be totally forbidden), so it's no surprise that your original intent was unclear. This is perhaps a completely new technique never before seen in Scala. The rules for setter and getter definitions were based on using them as getters and setters, so don't be surprised if things crack a little when you push at the boundaries like this.
It seems the real problem here is the way you're using type params. In this expression:
def editable_=[T <: HasEditable](value: Boolean) = (subject: T) => subject.setEditable(value)
The compiler has no way of inferring a particular T from the supplied argument, so it will take the most general type allowed (HasEditable in this case). You could change this behaviour by explicitly supplying a type param when using the method, but that would seem to defeat the entire point of what you're seeking to achieve.
Given that functions can't be generic (only methods can), I doubt that you even want type bounds at all. So one approach you could try is to just drop them:
def editable_=(value: Boolean) = (subject: HasEditable) => subject.setEditable(value)
def editable = new BindingMaker((widget: HasEditable) => SWTObservables.observeEditable(widget))