例如,javascript库具有此层次结构
class Base
class Foo:Base
class Bar:Base
和这个功能
calc(x:Base) : Int
calc(new Bar())
如何在PureScript中编写此函数?
foreign import calc :: ??? -> Int
答案 0 :(得分:1)
我认为这取决于你想对这些课程做些什么。我会做这样的事情:
-- 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
中,因为新实例会改变全局状态。