Haskell的类型类与Java函数重载

时间:2018-04-05 17:41:51

标签: java haskell typeclass

我一直在尝试理解Haskell的类型类,并经常阅读它们比java接口更通用。想一想,我想知道接口和类型类之间的比较实际上不是关系所在。我认为类型类应该与重载方法进行比较。请考虑以下Haskell代码:

class Divide a b c where
    divi :: a -> b -> c

instance Divide Integer Integer Double where
    divi x y = (fromIntegral x) `div` (fromIntegral y)

instance Divide Double Double Double where
    divi x y = x `div` y

instance Divide Double Integer Double where
    divi x y = x `div` (fromIntegral y)

instance Divide Integer Double Double where
    divi x y = (fromIntegral x) `div` y

写它"功能"在Java中(例如使用函数等静态方法)我会将其转换为以下内容

static class Math {

    static double divi(int a, int b) {
        return a / b;
    }

    static double divi(double a, double b) {
        // in java the implementation is always the same because the compiler does the trick, but that is irrelevant
        return a / b;
    }

    static double divi(double a, int b) {
        return a / b;
    }

    static double divi(int a, double b) {
        return a / b;
    }
}

我知道这不完全相同,因为在我的Java版本中没有等效的Divide Type类本身只存在重载函数。但我认为这比Haskell代码更接近于接口继承和方法覆盖。

你们怎么看待这个论点?

PS:我还没有在Haskell和Java中测试我的代码,因为它只是为了得到重点。请随时纠正任何错误。

0 个答案:

没有答案