Create a gist now

Instantly share code, notes, and snippets.

@ympbyc /bump.coffee
Last active Aug 17, 2016

Example usecases of JS-CLOS https://github.com/ympbyc/js-clos
#||||||||||||||||||||||||||||||||||||||||
#||||| example of multiple dispatch |||||
#||||||||||||||||||||||||||||||||||||||||
floor = define_class []
carpet = define_class []
ball = define_class []
glass = define_class []
bump = define_generic()
define_method bump, [ball, floor], -> 'bounce'
define_method bump, [glass, floor], -> 'crash'
define_method bump, [undefined, carpet], -> 'silence'
bump ball, floor #bounce
bump (make ball), (make floor) #bounce
bump glass, floor #crach
bump ball, carpet #silence
bump glass, carpet #silence
#|||||||||||||||||||||||||||||||||||
#||||| example of multimethods |||||
#|||||||||||||||||||||||||||||||||||
#fact
fact = define_generic()
define_method fact, [0], -> 1
define_method fact, ["number"], (n) ->
n * fact (n - 1)
fact 5
#=> 120
# import
c = require 'clos'
this[name] = fn for name, fn of c
#|||||||||||||||||||||||||||||||||||||||||||
#||||| example of multiple inheritance |||||
#|||||||||||||||||||||||||||||||||||||||||||
# domain
animal = define_class [], (x) ->
slot_exists x, 'voice', 'string'
cat = define_class [animal]
osx = define_class [], (x) ->
slot_exists x, 'hostname', 'string'
lion = define_class [cat, osx]
# definitions
say = define_generic()
define_method say, [animal], (a) -> a.voice
define_method say, [cat], (c) -> c.voice + ' meow'
hostname = define_generic()
define_method hostname, [osx], (o) -> o.hostname
# main
alice = make lion,
voice: 'roar'
hostname: 'example.com'
say alice
#=> 'roar meow'
hostname alice
#=> 'example.com'
@5alamander
5alamander commented May 9, 2016 edited

Is this a bug?

  var fib = define_generic(true); 
  define_method(fib, [0], () => {return 0;});
  define_method(fib, [1], () => {return 1;});
  define_method(fib, ["number"], (n) => {
    return fib(n-1) + fib(n-2);
  });
  define_method(fib, [undefined], () => {return "default";});

  /// .....
  console.log(fib(17));
  console.log(fib({}));
  console.log(fib("number")); // ... error
@ympbyc
Owner
ympbyc commented Aug 17, 2016

Sorry for a late reply. I haven't been active on github lately.
It seems to be a bug indeed. Somewhere around these lines: https://github.com/ympbyc/js-clos/blob/master/clos.js#L117
I'll look into it when I have time. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment