gpt4 book ai didi

haskell - 内函数作为幺半群

转载 作者:行者123 更新时间:2023-12-02 09:18:03 25 4
gpt4 key购买 nike

我正在尝试这个(出于学习目的):

{-# LANGUAGE FlexibleInstances #-}

instance Monoid (a -> a) where
mempty = id
mappend f g = f . g

期待id <> id等于 id . id

但是,与 (id <> id) 1我收到此错误:

Non type-variable argument in the constraint: Monoid (a -> a)

我应该改变什么来运行它?

这只是为了更好地理解幺半群和 Haskell 类型类,而不是为了任何实际用途

最佳答案

这需要 {-# OVERLAPPING #-}因为 GHC.Base 有一个 Monoid (a -> b) 的实例,所以 pragma当 b 是幺半群时:

{-# LANGUAGE FlexibleInstances #-}
import Data.Monoid (Monoid, mempty, mappend, (<>))

instance {-# OVERLAPPING #-} Monoid (a -> a) where
mempty = id
mappend f g = f . g

然后,即使a是一个Monoid,上面的实例也会被a -> a调用:

\> (id <> id) 1
1
\> (id <> id) [1]
[1]

而使用 Monoid b => a -> b 时,将调用 GHC.Base 中的实例:

\> ((:[]) <> (:[])) 1
[1,1]

请注意,Data.Monoid 提供 an exact same instance as yours for a -> a但使用 newtype Endo a 绕过了重叠.

关于haskell - 内函数作为幺半群,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37898555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com