Upgrade to Pro — share decks privately, control downloads, hide ads and more …

rho-contracts.js: Racket-style Higher-Order Con...

rho-contracts.js: Racket-style Higher-Order Contracts in Plain JavaScript

I presented rho-contracts.js as Hack and Tell NYC on May 20th, 2013. http://www.meetup.com/hack-and-tell/

The code is that https://github.com/sefaira/rho-contracts.js

Avatar for Guillaume Marceau

Guillaume Marceau

May 20, 2013

Other Decks in Programming

Transcript

  1. // derive: returns a function that is the // numerically-computed

    derivative // of the given function. function derive(fn, deltaX) { return function(x) { assert(_.isNumber(deltaX)) assert(_.isNumber(x)) assert(_.isFunctionFromNumberToNumber(fn)) // --> ??? } return (fn(x+deltaX/2) – fn(x-deltaX/2))/deltaX assert(_.isNumber(x))
  2. var derive : ((Float => Float), Float => (Float =>

    Float)) = Scala-Style function (fn, deltaX) { return function(x) { return (fn(x+deltaX/2) – fn(x-deltaX/2))/deltaX }
  3. var derive :: (Float -> Float) -> Float -> (Float

    -> Float) = Haskell-Style function (fn, deltaX) { return function(x) { return (fn(x+deltaX/2) – fn(x-deltaX/2))/deltaX }
  4. var derive = Rho-contracts-style fun fn: deltaX: fun x: number

    returns number number returns fun number returns number function (fn, deltaX) { return function(x) { return (fn(x+deltaX/2) – fn(x-deltaX/2))/deltaX }
  5. var derive = Rho-contracts-style c.fun({ fn: { deltaX: c.fun({ x:

    number }).returns(c.number) c.number }) .returns(c.fun({x: x.number}).returns(c.number) .wrap( function (fn, deltaX) { return function(x) { return (fn(x+deltaX/2) – fn(x-deltaX/2))/deltaX })
  6. configure.post ("/massing/:id/floors", [c.integerString], controller.massingFloorInfoSave, "massingFloorInfoSave", Nodejs + express.js + rho-contracts.js

    controller.massingFloorInfoSave, "massingFloorInfoSave", /* In: */ c.or(c.object({ numberOfFloors: c.integer }), c.object({ floorToFloorHeight: c.number })), /* Out: */ c.object({ floorToFloorHeight: c.optional(c.number), numberOfFloors: c.optional(c.integer) })
  7. // Calling with the wrong kind of function: // Calling

    with the arguments flipped: > derive(1.0, quadratic) ContractError: Expected fun, but got 1 For the `fn` argument of the call. // Forgetting an argument: > derive(quadratic) ContractError: Wrong number of arguments, expected 2 but got 1 // Calling with the wrong kind of function: > var fprime = derive(function(x) { return "**" + x + "**" }, 1.0) // There is now a contract-checking shell installed around //`fprime` that throws an error when `fprime` is called: > fprime(100) ContractError: `fn()` broke its contract Expected number, but got '**100.5**' for the return value of the call.
  8. github.com/sefaira/ rho-contracts.js download • catch some errors • submit some

    pull requests • we’re hiring c.any(c.query)? Guillaume Marceau sefaira.com senior software architect @gmarceau c.any(c.query)?