Haskell:如何将数据类型转换为其特定类型类之一? [英] Haskell : How to cast a data type to one of its specific typeclass?

查看:182
本文介绍了Haskell:如何将数据类型转换为其特定类型类之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将MySqlFakeClient和MySqlHttpClient强制转换为它们的通用类型类MySqlClient,而我却遇到了这个问题:

I want to cast MySqlFakeClient and MySqlHttpClient to their common typeclass MySqlClient and I have this issue :

对于以下代码:

loadClient :: MySqlClient client => String -> client
loadClient "fake" =  MySqlFakeClient 1 -- <- It's complaining here...
loadClient "prod" =  MySqlHttpClient "http://www.google.com"
loadClient _ = error "unknown"

data MySqlHttpClient = MySqlHttpClient String
data MySqlFakeClient = MySqlFakeClient Int

class MySqlClient client where
    config :: client -> String

instance MySqlClient MySqlHttpClient where

  config (MySqlHttpClient url) = url

instance MySqlClient MySqlFakeClient where

  config (MySqlFakeClient myInt) = show myInt

我们不能在Haskell中做到吗?

can't we do it in Haskell ?

推荐答案

此页面: https://wiki. haskell.org/Existential_type ,回答了我的问题(基本上使用存在性类型,例如建议使用@Rampion ...):

This page : https://wiki.haskell.org/Existential_type , answered my question (basically using existential types, like @Rampion suggested ...):

class Shape_ a where
   perimeter :: a -> Double
   area      :: a -> Double

 data Shape = forall a. Shape_ a => Shape a

 type Radius = Double
 type Side   = Double

 data Circle    = Circle    Radius
 data Rectangle = Rectangle Side Side
 data Square    = Square    Side


 instance Shape_ Circle where
   perimeter (Circle r) = 2 * pi * r
   area      (Circle r) = pi * r * r

 instance Shape_ Rectangle where
   perimeter (Rectangle x y) = 2*(x + y)
   area      (Rectangle x y) = x * y

 instance Shape_ Square where
   perimeter (Square s) = 4*s
   area      (Square s) = s*s

 instance Shape_ Shape where
   perimeter (Shape shape) = perimeter shape
   area      (Shape shape) = area      shape


 --
 -- Smart constructor
 --

 circle :: Radius -> Shape
 circle r = Shape (Circle r)

 rectangle :: Side -> Side -> Shape
 rectangle x y = Shape (Rectangle x y)

 square :: Side -> Shape
 square s = Shape (Square s)

 shapes :: [Shape]
 shapes = [circle 2.4, rectangle 3.1 4.4, square 2.1]

这篇关于Haskell:如何将数据类型转换为其特定类型类之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆