我正在尝试在 Haskell Book 中进行一项Semigroup练习(第15章Monoid,Semigroup )但我卡住了。以下给出:
newtype合并ab = 合并{unCombine ::(a - > b)}我应该写 Semigroup 实例为 Combine 。
然后书说它必须表现如下:
Prelude>让f =合并$ \\\ - >总和(n + 1)前奏> let g = Combine $ \\\ - > Sum(n - 1) Prelude> unCombine(f<> g)$ 0 Sum {getSum = 0} Prelude> unCombine(f< g)$ 1 Sum {getSum = 2} Prelude> unCombine(f<> f)$ 1 Sum {getSum = 4} Prelude> unCombine(g<> f)$ 1 Sum {getSum = 2}因此,我首先开始了一个错误的解决方案类型检查:
实例Semigroup(Combine ab)where 组合f<>合并g =合并f这当然没有预期的结果,但希望在右侧迈出一步方向。我的想法如下所示,使用伪码: pre code实例Semigroup(Combine ab)其中(Combine f )<> (Combine g)= Combine(SOMETHING)
SOMETHING 为: f 和 g 附加,无论具体的附加操作是什么(它取决于 f 和 g );所以我认为这需要来自 Data.Monoid 的<> ,但我已经有在我的代码中导入Data.Semigroup ,因此从 Data.Monoid 与 Data.Semigroup 中的一致。所以我应该怎么做?
我试图找出如何说明Combine(f Monoid's< g),但不能找出。
本书还指出,除非我使用GHC 8.x,否则我必须导入 Semigroup 和我可能会从 Monoid 中隐藏<> ;但我正在努力寻找如何产生这种效果。
有什么想法?
解决方案他们想要的可能是功能的增加。为此,输入 b 需要是一个半群:
import Data .Semigroup newtype Combine ab = Combine {unCombine ::(a - > b)} 实例Semigroup b =>半群(Combine a b)其中(Combine f)<> (Combine g)= Combine(\ x - > f x> g x)
I'm trying to do one of the Semigroup exercises in Haskell Book (Chapter 15, "Monoid, Semigroup") but I'm stuck. The following is given:
newtype Combine a b = Combine { unCombine :: (a -> b) }and I'm supposed to write the Semigroup instance for Combine.
And then book says that it must behave like the following:
Prelude> let f = Combine $ \n -> Sum (n + 1) Prelude> let g = Combine $ \n -> Sum (n - 1) Prelude> unCombine (f <> g) $ 0 Sum {getSum = 0} Prelude> unCombine (f <> g) $ 1 Sum {getSum = 2} Prelude> unCombine (f <> f) $ 1 Sum {getSum = 4} Prelude> unCombine (g <> f) $ 1 Sum {getSum = 2}So I first started with a wrong solution that type checks:
instance Semigroup (Combine a b) where Combine f <> Combine g = Combine fThat does not what is expected of course, but hopefully a step in the right direction. And my thinking is something like the following, in pseudocode:
instance Semigroup (Combine a b) where (Combine f) <> (Combine g) = Combine (SOMETHING)That SOMETHING being: f and g appended, whatever that concrete append operation is (it depends on f and g); so I think this requires <> from Data.Monoid, but I already have import Data.Semigroup in my code, and therefore <> from Data.Monoid coincides with the one from Data.Semigroup. So what am I supposed to do?
I tried to find out how I can state something like "Combine (f Monoid's <> g)", but couldn't find out.
The book also states unless I'm using GHC 8.x, I'll have to import Semigroup and that I might have "shadow" the <> from Monoid; but I'm struggling to find out how to have this effect.
Any ideas?
解决方案What they want is probably the addition of functions. For that, type b needs to be a Semigroup :
import Data.Semigroup newtype Combine a b = Combine { unCombine :: (a -> b) } instance Semigroup b => Semigroup (Combine a b) where (Combine f) <> (Combine g) = Combine (\x -> f x <> g x)
更多推荐
如何为此数据类型编写Semigroup实例?
发布评论