【发布时间】:2014-12-27 06:42:48
【问题描述】:
编辑:QWhere 的此类实例在传递如下输入时失败:>qWhere fly john 即使fly 是Argument -> Argument -> Predicate 类型并且john 是Argument 类型。
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
data Argument = Argument { ttype :: Type, value :: String } deriving (Show, Eq)
data Predicate = Predicate { lemma :: String, arguments :: [Argument] } deriving (Show, Eq)
class Fly a b where
fly :: a -> b -> Predicate
instance Fly Argument Argument where
fly x y = Predicate { lemma = "fly", arguments = [x, y] }
instance Fly Argument Predicate where
fly x y = Predicate { lemma = "fly", arguments = [x, arguments y !! 0] }
class QWhere a b where
qWhere :: a -> b -> String
instance QWhere (Argument -> Argument -> Predicate) Argument where
qWhere x y = "hi"
这是 ghci 的输出:
No instance for (QWhere (a0 -> b0 -> Predicate) Argument)
arising from a use of ‘qWhere’
The type variables ‘a0’, ‘b0’ are ambiguous
Note: there is a potential instance available:
instance QWhere (Argument -> Argument -> Predicate) Argument
-- Defined at new_context.hs:116:10
In the expression: qWhere fly john
In an equation for ‘it’: it = qWhere fly john
No instance for (Fly a0 b0) arising from a use of ‘fly’
The type variables ‘a0’, ‘b0’ are ambiguous
Note: there are several potential instances:
instance Fly Argument Predicate
-- Defined at new_context.hs:110:10
instance Fly Argument Argument
-- Defined at new_context.hs:107:10
In the first argument of ‘qWhere’, namely ‘fly’
In the expression: qWhere fly john
In an equation for ‘it’: it = qWhere fly john
这些问题是相关的,但没有一个答案能解决我的问题。
(1)Checking for a particular data constructor
(2)Test if Haskell variable matches user-defined data type option
还有一些互联网资源可以解决这个问题,但我找不到解决方案:
(3)https://www.haskell.org/haskellwiki/Determining_the_type_of_an_expression
(4)http://okmij.org/ftp/Haskell/typeEQ.html
我的问题:我定义了两种 Haskell data 类型。我得到了一个输入,我需要确定它是属于数据类型 A 还是数据类型 B。
这里是数据类型定义:
data Argument = Argument { ttype :: Type, value :: String } deriving (Show, Eq)
data Predicate = Predicate { lemma :: String, arguments :: [Argument] } deriving (Show, Eq)
如果变量是数据类型参数或谓词,我需要一个返回真/假的函数。
我试图遵循这两个 SO 问题的答案,但只收到 ghci 编译器的投诉:
--checks if a variable is of data type Argument
--this does not compile (from question (2))
isArgument :: a -> Bool
isArgument (Argument _) = True
isArgument _ = False
--from question (1), also fails
isArgument :: a -> String
isArgument value =
case token of
Argument arg -> "is argument"
Predicate p -> "is predicate"
【问题讨论】:
标签: haskell polymorphism