gpt4 book ai didi

haskell - 类型类和实例 : Pattern parameter becoming a list -- or not?

转载 作者:行者123 更新时间:2023-12-01 23:54:59 26 4
gpt4 key购买 nike

这里是 Haskell 新手 -- 我昨天遇到了这个问题,我就是无法理解。

最小工作示例

它可能不是那么简单,但它证明了我的问题——这里是:

data VectorFeatureSet feature = VFS [feature]

class FeatureSet fs where
getFeatures :: fs fl -> fl
instance FeatureSet VectorFeatureSet where
getFeatures (VFS fl) = fl -- <- error occurs here

(背景信息:) 关于这些类型含义的简短评论:Feature 是具有形状和一些可选属性的地理实体。 FeatureSet 只是一组属于一起的Feature

编译器在此代码段的最后一行抛出的错误:

Couldn't match expected type `fl' with actual type `[fl]'
`fl' is a rigid type variable bound by
the type signature for getFeatures :: VectorFeatureSet fl -> fl
at (mentioned line)
In the expression: fl
In an equation for `getFeatures': getFeatures (VFS fl) = fl
In the instance declaration for `FeatureSet VectorFeatureSet'

如果我将函数定义更改为

getFeatures (VFS [fl]) = fl

编译器接受它。

(旁注:我知道如果我使用命名字段表示法,Haskell 可以为我创建选择器函数,但我目前正在学习 Haskell,所以我是故意手写这些的。)

问题

现在,getFeatures 函数应该只是用于从 FeatureSet 中提取特征列表。我对模式的理解是,如果我不需要访问/处理列表的内容,我不需要用列表符号指定模式参数,而是可以从模式中获取列表并将其返回函数。

但在这里,Haskell 希望我使用像 fs -> [fl] -> fl 这样的函数定义来绑定(bind)像 fs -> fl -> fl 这样的签名(至少,我是这么理解的)。

所以我的问题是:为什么模式参数 fl 的类型在函数定义等式的左侧和右侧不同?

我觉得我在这里遗漏了一些基础知识,但我无法弄清楚要回到基础知识的哪一部分才能弄清楚 :(

最佳答案

给定 VectorFeatureSet 的定义,构造函数 VFS 的类型为 [fl] -> VectorFeatureSet fl,即它“包含”的值将是 fl列表

在您的 FeatureSet 实例中,getFeatures 的类型应该是 VectorFeatureSet fl -> fl

因此,当您编写 getFeatures (VFS fl) = fl 时,您将返回一个特征列表,而不是单个特征,因为变量 fltype [fl] - 请注意,类型和变量存在于不同的命名空间中。

这就是类型错误告诉你的 - 该函数应该返回 fl 类型的东西,但实际上产生了 [fl] 类型的东西。

当您编写 getFeatures (VFS [fl]) = fl 时,您实际上是针对单元素列表进行模式匹配,因此您的函数将失败,如果您尝试使用 VectorFeatureSet []VectorFeatureSet [x,y] 等调用它

根据 getFeatures 的名称和您对它的描述,听起来应该将其定义为

class FeatureSet fs where
getFeatures :: fs fl -> [fl]

关于haskell - 类型类和实例 : Pattern parameter becoming a list -- or not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339931/

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