[英]Function Types as Monoid Instances
I have a function that looks like this 我有一个看起来像这样的功能
transition :: State -> ([State], [State])
Given the particular domain of my problem, I know how to chain together two successive transition
function calls, something like this: 鉴于我的问题的特定领域,我知道如何将两个连续的
transition
函数调用链接在一起,如下所示:
transition `chain` trainsition ... `chain` transition
However, I would like to express this as a Monoid
and perform chaining with <>
and mappend
. 但是,我想将其表达为
Monoid
并使用<>
和mappend
进行链接。 Unfortunately, I cannot seem to get the following, or similar variants of, to work: 不幸的是,我似乎无法使用以下或类似的变体来工作:
instance Monoid (State -> ([State], [State])) where
mempty = ...
mappend = ...
The error returned is as follows: 返回的错误如下:
• 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]))’
In general, how can functions be expressed as instances of Monoid
? 一般来说,如何将函数表示为
Monoid
实例?
Functions are already instances of monoids in a different way . 函数已经以不同的方式实现了幺半群 。 How do you expect Haskell to decide to use that instance or your instance?
您如何期望Haskell决定使用该实例或您的实例? The usual way of solving your problem is to declare a
newtype
wrapper such as 解决问题的常用方法是声明一个
newtype
包装器,例如
newtype Transition a = Transition { runTransition :: a -> ([a], [a]) }
Then, you can make your monoid instance just fine: 然后,你可以使你的monoid实例正常:
instance Monoid (Transition a) where
mempty = ...
mappend = ...
After you are done this, you can may even find foldMap
useful. 完成后,您甚至可以找到
foldMap
有用。 Instead of writing something like 而不是写像
runTransition (Transition transition `chain`
Transition transition `chain`
...
Transition transition)
You can use foldMap
您可以使用
foldMap
runTransition (foldMap Transition [transition, transition, ... transition])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.