1

例如 javascript 库有这个层次结构

class Base
class Foo:Base
class Bar:Base

和这个功能

calc(x:Base) : Int
calc(new Bar())

你如何在 PureScript 中编写这个函数?

foreign import calc :: ??? -> Int
4

1 回答 1

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,因为创建新实例会改变全局状态。

于 2016-02-18T18:50:16.183 回答