2016-06-09 50 views
1

許多面向對象的腳本語言都有一個運算符或函數來測試某個對象是否爲給定元組或類型的實例。 JavaScript有instanceof操作,Python有一個內置isinstance以及一個issubclass內置等爲什麼不是'實例'這個單詞?

但在因素,所有元組類和對象類型都給出了自己的instance?字:

TUPLE: car speed ; 
! autogenerated is the word car?, which tests if something is a car 
TUPLE: boat weight ; 
! autogenerated is the word boat?, which tests if something is a boat 
100 boat boa boat? ! -> t 
100 boat boa car? ! -> f 

船是船和汽車都是汽車。汽車不是小船。

我們可以改寫的最後兩行,如:

100 boat boa boat instance-of? ! -> t 
100 boat boa car instance-of? ! -> f 

取而代之的是,在每一個因子對象都有自己專門的instance?字。這僅僅是爲了簡潔和可讀性,還是存在實現原因?

是否想爲某些原因定製某些對象上的instance?單詞?我們擁有仿製藥爲...

回答

1

instance-of?將工作大部分時間:

: instance-of? (obj cls -- ?) [ class-of ] dip class<= ; 
123 boat boa boat instance-of? . 
t 
123 boat boa tuple instance-of? . 
t 
123 fixnum instance-of? . 
t 

但它不是更復雜的類型不夠好:

QUALIFIED: math.primes 
PREDICATE: even < integer 2 mod 0 = ;  
PREDICATE: prime < integer math.primes:prime? ; 
7 prime? . 
t 
6 even? 
t 
7 prime instance-of? 
f 
6 even instance-of? . 
f 

另一個原因是優化。諸如fixnum?,string?array?之類的字在性能敏感的代碼中使用比更普通的instance-of?字更快速。

相關問題