函数类型为Monoid实例

时间:2017-06-27 14:44:49

标签: haskell functional-programming monoids

我有一个看起来像这样的功能

transition :: State -> ([State], [State])

鉴于我的问题的特定领域,我知道如何将两个连续的transition函数调用链接在一起,如下所示:

transition `chain` trainsition ... `chain` transition

但是,我想将其表示为Monoid并与<>mappend进行链接。不幸的是,我似乎无法使用以下或类似的变体:

instance Monoid (State -> ([State], [State])) where
    mempty  = ...
    mappend = ...

返回的错误如下:

• Illegal instance declaration for
    ‘Monoid (State -> ([State], [State]))’
    (All instance types must be of the form (T a1 ... an)
     where a1 ... an are *distinct type variables*,
     and each type variable appears at most once in the instance head.
     Use FlexibleInstances if you want to disable this.)
• In the instance declaration for
    ‘Monoid (State -> ([State], [State]))’

一般来说,如何将函数表示为Monoid

的实例

1 个答案:

答案 0 :(得分:7)

Functions are already instances of monoids in a different way。您如何期望Haskell决定使用该实例或您的实例?解决问题的常用方法是声明newtype包装器,例如

newtype Transition a = Transition { runTransition :: a -> ([a], [a]) }

然后,你可以让你的monoid实例很好:

instance Monoid (Transition a) where
  mempty  = ...
  mappend = ...

完成此操作后,您甚至可以发现foldMap有用。而不是写像

runTransition (Transition  transition `chain`
               Transition  transition `chain`
               ...
               Transition  transition)

您可以使用foldMap

runTransition (foldMap Transition [transition, transition, ... transition])