gpt4 book ai didi

haskell - 数据类型的空值是什么?

转载 作者:行者123 更新时间:2023-12-02 21:26:32 24 4
gpt4 key购买 nike

我有以下具有幺半群和半群实例的数据类型:

newtype Combine a b = 
Combine { unCombine :: a -> b }

instance (Semigroup b)
=> Semigroup (Combine a b) where
Combine {unCombine=f} <> Combine {unCombine=g} = Combine (f <> g)

instance (Semigroup b, Monoid b)
=> Monoid (Combine a b) where
mempty = Combine mempty
mappend = (<>)

我想配置它,函数(->)mempty值是多少?

我尝试过例如:

*Exercises Data.Monoid> mempty :: (-> Integer Bool)
<interactive>:21:15: error: parse error on input `Integer'

monoidmempty 的实现是什么样的?

我查看了黑客源代码:

instance Monoid b => Monoid (a -> b) where
mempty _ = mempty
mappend f g x = f x `mappend` g x

并且找不到mempty的实现。

也许为了澄清我的意思,请考虑以下示例:

*Exercises Data.Monoid> mempty :: (Product Integer)
Product {getProduct = 1}

Product Integer 的内存为 Product {getProduct = 1}

最佳答案

  1. 类型构造函数 (->)不是类型常量(没有任何 (->) 类型的值),因此不能有幺半群实例。
  2. 如果输入 b有一个幺半群实例,类型常量 a -> b (或 (->) a b )确实有一个幺半群实例和 mempty生成一个函数,该函数忽略其输入并返回 memptyb作为值(value)。

如果你看

instance Monoid <b>b</b> => Monoid (a -> <b>b</b>) where
mempty _ = <b>mempty</b>
mappend f g x = f x `<b>mappend</b>` g x

线路mempty _ = <strong>mempty</strong>实现了这个。

mempty 的类型是什么对于 a -> b ?是a -> b ,如mempty需要是 a -> b 类型的值。所以

mempty _ = <strong>mempty</strong>

告诉我们,mempty对于 a -> b是一个函数,它丢弃其输入并返回 mempty , b 类型的值。名称 mempty 两次出现在此定义中指的是不同的函数/值。

让我们举一些具体的例子:

  1. 您已尝试

    mempty :: (-> Integer Bool)

    这在语法上是错误的。你想尝试

    mempty :: (->) Integer Bool

    这会产生一个新的错误

    <interactive>:5:1: error:
    • No instance for (Monoid Bool) arising from a use of ‘mempty’
    • In the expression: mempty :: (->) Integer Bool
    In an equation for ‘it’: it = mempty :: (->) Integer Bool

    Bool没有幺半群实例。

  2. 您已尝试

    mempty :: (Product Integer)

    它有效并产生了 Product {getProduct = 1}作为值(value)。这告诉你,Product Integer有一个幺半群实例。因此我们可以尝试拥有 Product Integer作为类型 b a -> <strong>b</strong> .

  3. 现在尝试

    > let f = mempty :: a -> Product Integer
    > f 'x'
    Product {getProduct = 1}

    在此示例中mempty引用 a -> Product Integer 类型的某个值因此 是一个函数。所以类型变量 t来自mempty :: (Monoid t) => t指类型a -> Product Integer在这种情况下。

关于haskell - 数据类型的空值是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44818972/

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