3 ms·
The best way would be to specify the return type directly. This is unfortunate, but it is how basically any language (that I know) save Haskell would do it. So
by tikhonj 14y ago
The best way would be to specify the return type directly. This is unfortunate, but it is how basically any language (that I know) save Haskell would do it.
So instead of having a return function, you would use something like List.return or Maybe.return or whatever. This is the same way you would solve the problem of read (that is, the opposite of toString): Double.parse, Integer.parse and so on. When you have a polymorphic function, you would pass in the type as appropriate.
Clearly, this is not ideal. However, this is basically what the Haskell compiler does for you with typeclasses--loosely speaking, a function polymorphic over a typeclass gets transformed into a function accepting an instance and its normal arguments.
In OCaml, you could solve this problem with a functor. So your polymorphic module is parametrized on another module that provides the return and bind functions. I personally like this approach less than Haskell's, but it is more flexible (for better or worse): you can have different modules passed in for the same type. In Haskell, to get different behavior for the same type using typeclasses, you'd have to create a new type with newtype.
So in short, it isn't impossible: you just have to do more manually than you do in Haskell.
- Peaker 14y agoIf you want to write functions that are polymorphic on any monad, they'd have to take a type argument explicitly, which also reduces their cost-effectiveness. I am not sure Monads are a cost-effective abstraction in most languages.