首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据类型中的Haskell数据类型

数据类型中的Haskell数据类型
EN

Stack Overflow用户
提问于 2021-05-28 03:15:41
回答 1查看 96关注 0票数 0

假设我有像data Shape = Circle Size | Rectangle CornerSize这样的数据类型,Corner也是不同的数据类型,比如data Size = Big | Small deriving (Show, Eq, Ord)data Corner = Blunt | Sharp Size deriving (Show, Eq, Ord)

我想编写一个返回Big而不是Circle Big的函数。最好的方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-29 17:38:18

我估计您需要一个提取形状的主属性的函数,所以如下所示:

代码语言:javascript
复制
> getAttr (Circle Big)
Big
> getAttr (Rectangle Blunt)
Blunt
> getAttr (Rectangle (Sharp Small))
Sharp Small

从技术上讲这是可能的。您可以编写一个类型类:

代码语言:javascript
复制
class GetAttr a where
  getAttr :: Shape -> a
instance GetAttr Size where
  getAttr (Circle s) = s
instance GetAttr Corner where
  getAttr (Rectangle c) = c

要定义这样的函数,必须帮助GHCi处理以下类型:

代码语言:javascript
复制
λ> getAttr (Circle Big) :: Size
Big
λ> getAttr (Rectangle Blunt) :: Corner
Blunt
λ> getAttr (Rectangle (Sharp Small)) :: Corner
Sharp Small

如果您请求错误的类型,您将得到一个运行时错误:

代码语言:javascript
复制
λ> getAttr (Rectangle Blunt) :: Size
*** Exception: OneAttribute.hs:9:3-24: Non-exhaustive patterns in function getAttr

因此,它可能是返回一个Maybe

代码语言:javascript
复制
class GetAttr a where
  getAttr :: Shape -> Maybe a
instance GetAttr Size where
  getAttr (Circle s) = Just s
  getAttr _ = Nothing
instance GetAttr Corner where
  getAttr (Rectangle c) = Just c
  getAttr _ = Nothing

给予:

代码语言:javascript
复制
λ> getAttr (Rectangle Blunt) :: Maybe Corner
Just Blunt
λ> getAttr (Rectangle Blunt) :: Maybe Size
Nothing

但是,既然您有了这个函数,通常您会发现它并不是很有用。几乎每次使用它时,您都会发现您已经确切地知道了所期望的属性类型是Size还是Corner,因此您可以用更简单、更清晰的函数替换getAttr

代码语言:javascript
复制
getSize :: Shape -> Maybe Size
getSize (Circle s) = Just s
getSize _ = Nothing

getCorner :: Shape -> Maybe Corner
getCorner (Rectangle c) = Just c
getCorner _ = Nothing

或者完全放弃这些函数,当您发现自己需要提取形状的主要属性时,直接在Shape上进行案例匹配:

代码语言:javascript
复制
printAttribute :: Shape -> String
printAttribute (Circle s) = "shape: " ++ show s
printAttribute (Rectangle c) = "corner: " ++ show c
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67732436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档