haskell - 我可以表达一个子类约束吗?
问题描述
仍然在玩存在主义而不是约束(只是探索这个设计空间,我知道许多 Haskeller 认为它很糟糕)。有关更多信息,请参阅此问题。
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ConstraintKinds #-}
{-# Language TypeApplications #-}
import GHC.Exts (Constraint)
class Foo a where
foo :: a -> Int
class Foo a => Bar a where
bar :: a -> String
instance Foo Int where
foo = id
instance Bar Int where
bar = show
data Obj cls = forall o. (cls o) => Obj o
fooable = Obj @Foo $ (42 :: Int)
barable = Obj @Bar $ (42 :: Int)
doFoo :: Obj Foo -> Int
doFoo (Obj x) = foo x
现在我有这个问题。doFoo fooable
有效,但doFoo barable
没有。
• Couldn't match type ‘Bar’ with ‘Foo’
Expected type: Obj Foo
Actual type: Obj Bar
• In the first argument of ‘doFoo’, namely ‘barable’
In the expression: doFoo barable
In an equation for ‘it’: it = doFoo barable
这当然是真的。Obj Foo
是不同的Obj Bar
。
我可以给一个合适的类型doFoo
吗?基本上我想要一种类型,Obj cls where cls is a subclass of Foo
但我找不到表达它的方法。请多多包涵,我对这些狂野的奇妙类型是新手。
解决方案
您可以为此使用量化约束:
{-# LANGUAGE QuantifiedConstraints #-}
doFoo :: forall c . (forall a. c a => Foo a) => Obj c -> Int
doFoo (Obj x) = foo x
本质上,doFoo
采用 any Obj c
,其中c
任何类型类都暗示Foo
,即满足量化约束的类型类
forall a. c a => Foo a
推荐阅读
- java - 如何检查图像是否已在本地存在
- amazon-web-services - AWS Amplify:从其他放大环境添加现有资源
- awk - 为什么我的 AWK 脚本等待我按下一个键?
- ios - UIWindow 没有为新设备填满屏幕?
- model - 返回文字 JSON 而不是 __str__ Django Rest Framework
- c# - 仅使用文本框创建电子表格
- graphql - 如何使用 apollo 客户端在 GraphQl 查询中传递多个字符串参数
- android - Flutter build appbundle 不创建 64bit 并添加不必要的权限?
- javafx - 在JavaFX程序中的maven编译期间Victorlaerte AsyncTask libray错误
- c++ - C++ 内聚与类 Date