簡體   English   中英

函數類型為Monoid實例

[英]Function Types as Monoid Instances

我有一個看起來像這樣的功能

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實例?

函數已經以不同的方式實現了幺半群 您如何期望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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM