从 javascript 继承的惯用方法是什么?
What is the idiomatic way to work with inheritance from javascript?
例如 javascript 库具有此层次结构
class Base
class Foo:Base
class Bar:Base
和这个函数
calc(x:Base) : Int
calc(new Bar())
如何用 PureScript 编写这个函数?
foreign import calc :: ??? -> Int
我认为这取决于您想用这些 类 做什么。我会做这样的事情:
-- purs file
foreign import data Base :: *
foreign import data Foo :: *
foreign import data Bar :: *
fooToBase :: Foo -> Base
fooToBase = unsafeCoerce
barToBase :: Bar -> Base
barToBase = unsafeCoerce
foreign import newFoo :: forall e. Eff e Foo
foreign import newBar :: forall e. Eff e Bar
-- works with all ancestors
foreign import calc :: Base -> Eff e Unit
-- works only with Foos
foreign import fooMethod :: String -> Foo -> Eff e Int
-- using
main = do
foo <- newFoo
bar <- newBar
calc $ fooToBase foo
calc $ barToBase bar
fooMethod "test" foo
-- js file
exports.newFoo = function() { return new Foo(); };
exports.newBar = function() { return new Bar(); };
exports.calc = function(o) {
return function() {
return o.calc();
};
};
exports.fooMethod = function(str) {
return function(o) {
return function() {
return o.fooMethod();
};
};
};
这里的一切都应该存在于 Eff
中,因为创建新实例会改变全局状态。
例如 javascript 库具有此层次结构
class Base
class Foo:Base
class Bar:Base
和这个函数
calc(x:Base) : Int
calc(new Bar())
如何用 PureScript 编写这个函数?
foreign import calc :: ??? -> Int
我认为这取决于您想用这些 类 做什么。我会做这样的事情:
-- purs file
foreign import data Base :: *
foreign import data Foo :: *
foreign import data Bar :: *
fooToBase :: Foo -> Base
fooToBase = unsafeCoerce
barToBase :: Bar -> Base
barToBase = unsafeCoerce
foreign import newFoo :: forall e. Eff e Foo
foreign import newBar :: forall e. Eff e Bar
-- works with all ancestors
foreign import calc :: Base -> Eff e Unit
-- works only with Foos
foreign import fooMethod :: String -> Foo -> Eff e Int
-- using
main = do
foo <- newFoo
bar <- newBar
calc $ fooToBase foo
calc $ barToBase bar
fooMethod "test" foo
-- js file
exports.newFoo = function() { return new Foo(); };
exports.newBar = function() { return new Bar(); };
exports.calc = function(o) {
return function() {
return o.calc();
};
};
exports.fooMethod = function(str) {
return function(o) {
return function() {
return o.fooMethod();
};
};
};
这里的一切都应该存在于 Eff
中,因为创建新实例会改变全局状态。