Вопрос

instance Monad (Either a) where
     return = Left
     fail = Right
     Left x >>= f = f x
     Right x >>= _ = Right x

Этот код frag в 'baby.hs' вызвал ошибку ужасной компиляции:

Prelude> :l baby
[1 of 1] Compiling Main             ( baby.hs, interpreted )

baby.hs:2:18:
Couldn't match expected type `a1' against inferred type `a'
  `a1' is a rigid type variable bound by
       the type signature for `return' at <no location info>
  `a' is a rigid type variable bound by
      the instance declaration at baby.hs:1:23
In the expression: Left
In the definition of `return': return = Left
In the instance declaration for `Monad (Either a)'

baby.hs:3:16:
Couldn't match expected type `[Char]' against inferred type `a1'
  `a1' is a rigid type variable bound by
       the type signature for `fail' at <no location info>
  Expected type: String
  Inferred type: a1
In the expression: Right
In the definition of `fail': fail = Right

baby.hs:4:26:
Couldn't match expected type `a1' against inferred type `a'
  `a1' is a rigid type variable bound by
       the type signature for `>>=' at <no location info>
  `a' is a rigid type variable bound by
      the instance declaration at baby.hs:1:23
In the first argument of `f', namely `x'
In the expression: f x
In the definition of `>>=': Left x >>= f = f x

baby.hs:5:31:
Couldn't match expected type `b' against inferred type `a'
  `b' is a rigid type variable bound by
      the type signature for `>>=' at <no location info>
  `a' is a rigid type variable bound by
      the instance declaration at baby.hs:1:23
In the first argument of `Right', namely `x'
In the expression: Right x
In the definition of `>>=': Right x >>= _ = Right x
Failed, modules loaded: none.

Почему это случится? И как я могу сделать этот код компилировать? Спасибо за любую помощь ~

Понимаю. И я настроил код, чтобы увидеть его компилирования:

instance Monad (Either a) where
     return = Right
     Left a >>= f = Left a
     Right x >>= f = f x

Это успешно компилируется! Но ... для еще более вопроса:

instance Monad (Either a)

делает «либо« монадом, и я получил «возвращение = правильно» ... как я могу получить «return = lever»? Я пробовал это, но потерпел неудачу:

instance Monad (`Either` a) where
     return = Left
     Right a >>= f = Right a
     Left x >>= f = f x

или: экземпляр монад ( x -> либо xa)

Не сознает вообще!

Это было полезно?

Решение

  1. Возврат должен иметь тип forall b. b -> Either a b, Однако у вас есть тип forall c. a -> Either a c. Отказ Вы, вероятно, хотите прямо здесь.
  2. fail должен иметь тип forall b. String -> Either a b, Однако имеет право имеет тип forall b. b -> Either a b, так что если b=String что делает String -> Either a String который не подходит.
  3. >>= должен иметь тип Either a b -> (b -> Either a c) -> Either a c Однако Right x >>= _ = Right x всегда возвращает значение типа Either a b, нет Either a c.
  4. Left x >>= f = f x не работает, потому что X имеет тип a, но f имеет тип b -> c.

Другие советы

Большая часть путаницы связана с фактом, и вправо используются в обратном направлении. Учитывая только тип возврата, его тип из Monad TypeClass выглядит следующим образом:

return :: (Monad m) => b -> m b

Вы пытаетесь определить экземпляр для m = Either a, поэтому возврат должен иметь тип:

return :: b -> Either a b

Вы определяете его как слева, который имеет тип:

Left :: a -> Either a b

Обратите внимание, как левая сторона -> отличается

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top