139 points · by swannodette · 15y ago · 34 comments
This Lambda The Ultimate discussion on Benjamin C. Pierce's (Types And Programming Languages) talk Types Considered Harmful is also of interest - the gist being that contracts are useful because sometimes static types are just too damn hard - http://lambda-the-ultimate.org/node/2828
EDIT: Might as well link to Brendan Eich's talk Proxies Are Awesome!, http://www.slideshare.net/BrendanEich/metaprog-5303821. I haven't really been following the Proxy thing and they seem quite useful. It's nice to see them applied so powerfully here.
Also +1 to be able to define your own type.
guardArgs = (def, args) ->
i = 0
for arg, type of def
throw new Error("bad type of #{arg}") unless typeof args[i] == type
i++
typeEnsure = (def, f) -> ->
guardArgs(def, arguments)
f.apply @, arguments
myFunc = typeEnsure {name: 'string', i: 'number'}, (name, i) ->
console.log name, i
myFunc("foo", 1) # ok
myFunc("foo", "x") # Error: bad type of i
I think this can be extended to custom types too.Second, you need proxies to handle things like functions and mutable arrays.
Third, that there's a DSL for describing contracts is, I think, a large part of the point.
https://github.com/cappuccino/cappuccino/blob/master/Objecti...
f :: ((Num) -> Bool, Num) -> Bool
The type of f is not particularly obvious to me; instinctively, it could either be:1. A function that takes (a function from Num to [Bool, Num]) and returns Bool, or
2. A function that takes (a function from Num to Bool) and a Num, and returns a Bool.
Given enough time, I'm going to guess 2, but this makes CoffeeScript's destructing assignment, IE
[a, b] = func()
feel less 'first class'. Is this a serious ambiguity, or just me not having enough experience with precedence in CoffeeScript/functional languages? f :: ((Num) -> [Bool, Num]) -> Bool
DaveI mention this briefly towards the end of the quick start section of the doc: http://disnetdev.com/contracts.coffee/#quickstart
[1] https://github.com/disnet/contracts.coffee/blob/master/src/l...
[2] https://github.com/disnet/contracts.coffee/blob/master/src/l...
Also, I believe other DBC platforms had options to disable run time enforcing of contracts, is this possible somehow with CFCS ?
If you compile with "coffee -c" (compile, no contracts) instead of "coffee -cC" (compile, with contracts) you get pure JavaScript, no contracts and no runtime checks. Exactly what vanilla CoffeeScript would have given you.
the CoffeeScript version is nice though :D
isEven = (x) ->
x % 2 is 0
f :: (!isOdd) -> !isEven
f = (x) -> ...To quote Jeremy Ashkenas's JSConf talk on forking CoffeeScript: "when in doubt, cheat." ;-P
But we would still like to express and enforce some invariants about our code. And we'd like to do it in a more elegant way than constantly writing "if(argument === ...) then ... else ..."
Contracts also allow us to check invariants that might not result in a run-time exception but could lead to the code just being subtly wrong.