factor/library/generic/math-combination.factor

76 lines
1.9 KiB
Factor
Raw Normal View History

2005-08-19 21:46:12 -04:00
! Copyright (C) 2005 Slava Pestov.
! See http://factor.sf.net/license.txt for BSD license.
IN: generic
USING: errors generic hashtables kernel kernel-internals lists
math namespaces sequences words ;
2005-08-16 15:53:30 -04:00
! Math combination for generic dyadic upgrading arithmetic.
: math-priority ( class -- n )
2006-05-02 03:05:57 -04:00
dup "members" word-prop [
0 [ math-priority max ] reduce
] [
"math-priority" word-prop [ 100 ] unless*
] ?if ;
: math-class< ( class class -- ? )
[ math-priority ] 2apply < ;
: math-class-max ( class class -- class )
[ swap math-class< ] 2keep ? ;
: math-upgrade ( left right -- quot )
2dup math-class< [
nip "coercer" word-prop
dup [ [ >r ] swap [ r> ] append3 ] when
] [
2dup swap math-class< [
drop "coercer" word-prop
] [
2drop [ ]
2005-09-24 15:21:17 -04:00
] if
] if ;
TUPLE: no-math-method left right generic ;
: no-math-method ( left right generic -- )
2005-09-17 22:25:18 -04:00
3dup <no-math-method> throw ;
: applicable-method ( generic class -- quot )
2005-09-25 20:41:49 -04:00
over "methods" word-prop hash
[ ] [ [ no-math-method ] curry ] ?if ;
: object-method ( generic -- quot )
2005-11-24 19:02:20 -05:00
object bootstrap-word applicable-method ;
: math-method ( word left right -- quot )
2006-01-09 01:34:23 -05:00
2dup and [
2dup math-upgrade >r
math-class-max over order min-class applicable-method
r> swap append
] [
2drop object-method
2005-09-24 15:21:17 -04:00
] if ;
: math-vtable ( picker quot -- quot )
[
swap , \ tag ,
2006-01-09 01:34:23 -05:00
[ num-tags [ type>class ] map swap map % ] { } make ,
\ dispatch ,
2005-08-25 15:27:38 -04:00
] [ ] make ; inline
: math-class? ( object -- ? )
2005-09-24 15:21:17 -04:00
dup word? [ "math-priority" word-prop ] [ drop f ] if ;
: math-combination ( word -- quot )
\ over [
2006-01-09 01:34:23 -05:00
dup math-class? [
2005-08-16 15:53:30 -04:00
\ dup [ >r 2dup r> math-method ] math-vtable
] [
over object-method
2005-09-24 15:21:17 -04:00
] if nip
2005-08-16 15:53:30 -04:00
] math-vtable nip ;
PREDICATE: generic 2generic ( word -- ? )
"combination" word-prop [ math-combination ] = ;