1 |
Мова програмування Haskell славиться своєю сильною системою типів, яка допомагає уникати багатьох типових помилок під час компіляції програм. Однак іноді виникають ситуації, коли компілятор не може вивести тип деяких виразів автоматично, що може стати причиною непередбачуваних помилок. Однією з таких проблем є виведення типів у монаді Writer після використання оператора послідовності. Давайте розберемося, чому ця проблема виникає і як її можна вирішити. |
1 |
Розглянемо наступний код: |
1 2 3 4 5 6 7 8 9 |
import Control.Monad.Writer class Foo c where fromInt :: Int -> c instance Foo [Int] where fromInt n = [n] instance (Monoid c, Foo c) => Foo (Writer c ()) where fromInt d = writer ((), fromInt d) onetwo :: Writer [Int] () onetwo = fromInt 1 >> fromInt 2 |
1 |
Після компіляції отримуємо наступну помилку: |
1 2 3 |
Ambiguous type variable `a0' arising from a use of `fromInt' prevents the constraint `(Foo (WriterT [Int] Data.Functor.Identity.Identity a0))' from being solved. So it looks like Haskell fails to infer the return type of the Writer monad, but I don't understand why, since it can only be the unit type based on the implementation of fromInt. Why does Haskell fail to infer this? |