我有一个自定义数据类型Foo = Foo{ a :: Int, b :: Int},我正在尝试使Foo成为自定义读取实例.我已经有了一个功能bar :: String -> Foo,我尝试这样做:
instance Read (Foo a b) where
read s = bar s
Run Code Online (Sandbox Code Playgroud)
但是当我将文件加载到GHCi中进行测试时,我收到以下错误: Fraction.hs:11:1: read' is not a (visible) method of class Read'
有人能告诉我问题是什么以及我如何实际实例化这种类型?
所以我有一个数据类型
data SomeType a =
Type a |
Mix (SomeType a) (SomeType a)
Run Code Online (Sandbox Code Playgroud)
这是SomeType的show实例
instance (Show a) => Show (SomeType a) where
show (Type a) = show a
show (Mix a b) = "(" ++ show a ++ " " ++ show b ++ ")"
Run Code Online (Sandbox Code Playgroud)
所以
Mix (Type 5) (Type 4)
Run Code Online (Sandbox Code Playgroud)
会给我的
(5 4)
Run Code Online (Sandbox Code Playgroud)
现在我想拥有
read "(3 4)" :: SomeType Int
Run Code Online (Sandbox Code Playgroud)
生产
(3 4)
Run Code Online (Sandbox Code Playgroud)
要么
read "(a b)" :: SomeType Char
Run Code Online (Sandbox Code Playgroud)
生产
(a b)
Run Code Online (Sandbox Code Playgroud)
我迷失在如何使用Read类.
哈斯凯勒同学们大家好,
\n\n我现在正在学习 Haskell 一个月,并且正在努力为个人数据类型创建自定义读取实例。
\n\n我遵循了这一点以及Learn Yourself a Haskell 中的相关章节,这是我的代码片段。
\n\ndata Position = Position (Absc,Ordn) deriving (Show)\ninstance Read (Position) where\nreadsPrec _ input =\n let absc = List.filter (/=\'(\') $ takeWhile (/=\',\')\n ordn = List.filter (/=\')\') $ tail (dropWhile (/=\',\') )\n in (\\str -> Position ( (read (absc str) :: Int)\n , (read (ordn str) :: Int) ) ) input\ntype Absc = Int\ntype Ordn = Int\nRun Code Online (Sandbox Code Playgroud)\n\n我的目标是解析输入"(1,3)"以输出类似的内容Position (1,3)
但是,我收到以下错误消息:
\n\n …当我在ghci中编译我的代码时,没有问题.它可以正确编译.但是,如果我尝试在拥抱中编译它,我会收到错误"编译代码太复杂".我认为问题是由于许多|条件造成的.
如果我将其更改为使用if/else,则没有问题.我可以添加if/else语句100次,但这将非常烦人和恼人.而不是那样,我试图在20-30 |条件之后放置if/else语句,但是|如果语句如下所示我无法进行工作:
f x y z
| cond1 = e1
| cond2 = e2
...
if (1)
then
| cond30 = e30
| cond31 = e31
...
else
| cond61 = e61
| cond62 = e62
Run Code Online (Sandbox Code Playgroud)
如何以最少的努力修复代码?完整的代码在hpaste上,因为它比StackOverflow的问题大小限制更长.