LINUX.ORG.RU

История изменений

Исправление qnikst, (текущая версия) :

классы типов являются открытыми, собственно доопределением ты и будешь заниматься.

Prelude> :set -XMultiParamTypeClasses
Prelude> class MyPlus a b c where (+:) :: a -> b -> c
Prelude> instance MyPlus Float Int Float where a +: b = a + fromIntegral b
Prelude GHC.Float> instance MyPlus Float Int Double where a +: b = float2Double  $ a +: b
Prelude GHC.Float> (2.0 :: Float) +: (1::Int)

<interactive>:10:1:
    No instance for (MyPlus Float Int a0) arising from a use of ‘it’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance MyPlus Float Int Double -- Defined at <interactive>:9:10
      instance MyPlus Float Int Float -- Defined at <interactive>:6:10
    In the first argument of ‘print’, namely ‘it’
    In a stmt of an interactive GHCi command: print it

Prelude GHC.Float> (2.0 :: Float) +: (1::Int) :: Double
3.0
Prelude GHC.Float> :t it
it :: Double

Кстати, а как проверить, например, что a типа Float?

может стоит учить язык последовательно? ;)

P.S. кстати 2 инстанса отличающиеся возвращаемым значением при одинаковых параметрах могут порадовать некоторые другие ЯП. Как я понимаю в ракетке про это и писали, почему отказались от тайпклассов (третья причина).

Исходная версия qnikst, :

классы типов являются открытыми, собственно доопределением ты и будешь заниматься.

Prelude> :set -XMultiParamTypeClasses
Prelude> class MyPlus a b c where (+:) :: a -> b -> c
Prelude> instance MyPlus Float Int Float where a +: b = a + fromIntegral b
Prelude GHC.Float> instance MyPlus Float Int Double where a +: b = float2Double  $ a +: b
Prelude GHC.Float> (2.0 :: Float) +: (1::Int)

<interactive>:10:1:
    No instance for (MyPlus Float Int a0) arising from a use of ‘it’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance MyPlus Float Int Double -- Defined at <interactive>:9:10
      instance MyPlus Float Int Float -- Defined at <interactive>:6:10
    In the first argument of ‘print’, namely ‘it’
    In a stmt of an interactive GHCi command: print it

Prelude GHC.Float> (2.0 :: Float) +: (1::Int) :: Double
3.0
Prelude GHC.Float> :t it
it :: Double

Кстати, а как проверить, например, что a типа Float?

может стоит учить язык последовательно? ;)