Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 基于类选择函数_Haskell_Typeclass - Fatal编程技术网

Haskell 基于类选择函数

Haskell 基于类选择函数,haskell,typeclass,Haskell,Typeclass,不管怎样,即使使用GHC扩展的奇怪组合,是否也会使函数h类似于以下代码: f :: (C1 a) => a -> Int g :: (C2 a) => a -> Int h x = if (isOfClass C1 x) then (f x) else if (isOfClass C2 x) then (g x) else COMPILE_ERROR 请注意,如果x同时属于C1和C2两类,则我不介意根据范围内的内容出现不一致的行为 将值包装为另一种类型

不管怎样,即使使用GHC扩展的奇怪组合,是否也会使函数
h
类似于以下代码:

f :: (C1 a) => a -> Int
g :: (C2 a) => a -> Int

h x = 
  if (isOfClass C1 x) then (f x) 
  else if (isOfClass C2 x) then (g x)
  else COMPILE_ERROR

请注意,如果
x
同时属于
C1
C2
两类,则我不介意根据范围内的内容出现不一致的行为

将值包装为另一种类型,例如
或自定义类型

带有
的示例:

h :: (C1 a, C2 b) => Either a b -> Int
h = either f g

这是不可能的,因为它将处理单独的编译。考虑

module A where

data A = A Int

isOfClassEq :: a -> Bool
isOfClassEq = <<some magic here>>

test :: Bool
test = isOfClassEq (A 42)
如果我在GHCi中打开模块
A
test
将计算为
False
。因此,与
test
关联的代码必须返回
False
。相反,如果我加载模块
Main
并运行
Main
,我应该会看到
True
。如果我们有单独的编译,由于编译器在编译模块
A
时无法知道实例,因此is必须为
测试生成代码,该测试在运行时检查类成员资格


这将要求GHC在运行时保留所有类型信息,包括执行检查的typeclass表。但是,Haskell的设计是为了在编译时丢弃类型信息。

您是否考虑过使用案例?
module Main where
import A
instance Eq A where (A x) == (A y) = x == y
main = print test