读取自定义数据类型失败
Fail to read a self defined data type
data MyNum = One
| Two
| Three
deriving (Show, Eq)
我只是用构造函数 One
、Two
和 Three
定义了 MyNum
。
*Main> :t One
One :: MyNum
但是当我将 x = read("One")::MyNum
添加到我的程序时 ghci 会产生错误:
No instance for (Read MyNum) arising from a use of ‘read’
In the expression: read ("One") :: MyNum
In an equation for ‘x’: x = read ("One") :: MyNum
为什么我不能 read
它?
您必须在 MyNum
的定义中导出 Read
:
data MyNum = One
| Two
| Three
deriving (Show, Eq, Read)
x = read("One")::MyNum
*Main> x
One
data MyNum = One
| Two
| Three
deriving (Show, Eq)
我只是用构造函数 One
、Two
和 Three
定义了 MyNum
。
*Main> :t One
One :: MyNum
但是当我将 x = read("One")::MyNum
添加到我的程序时 ghci 会产生错误:
No instance for (Read MyNum) arising from a use of ‘read’
In the expression: read ("One") :: MyNum
In an equation for ‘x’: x = read ("One") :: MyNum
为什么我不能 read
它?
您必须在 MyNum
的定义中导出 Read
:
data MyNum = One
| Two
| Three
deriving (Show, Eq, Read)
x = read("One")::MyNum
*Main> x
One