[英]Haskell: functions in custom data types
if I have a custom data type that takes in a string representation of a Boolean
(ie "true"
or "false"
). 如果我有一个采用Boolean
的字符串表示形式的自定义数据类型(即"true"
或"false"
)。 How do I make by data type convert that to a Bool
with out having to perform an actions on the input before? 如何通过数据类型将其转换为Bool
,而无需之前对输入执行任何操作?
for example 例如
λ: MyData "false"
MyData False
You can't without a function, normally you just define a function that returns the new type, for instance: 您不能没有函数,通常只需定义一个返回新类型的函数即可,例如:
newtype MyData = MyData Bool
myData :: String -> MyData
myData "false" = MyData False
myData "true" = MyData True
-- Need to decide how to handle invalid arguments
Now instead of writing MyData "false"
you write myData "false"
. 现在,不用编写MyData "false"
而是编写myData "false"
。
You can also use the OverloadedStrings
extension in GHC and declare your type to be an instance of IsString
: 您还可以在GHC中使用OverloadedStrings
扩展,并将您的类型声明为IsString
的实例:
newtype MyData = MyData Bool deriving (Show)
instance IsString MyData where
fromString "false" = MyData False
fromString "true" = MyData True
fromString "False" = MyData False
fromString "True" = MyData True
Now you can say something like: 现在您可以说:
> "false" :: MyData
MyData False
> "True" :: MyData
MyData True
You simply can't. 你根本做不到。
First, String
type has values irrepresentable as Boolean
, like "foo"
. 首先, String
类型具有不可表示为Boolean
,例如"foo"
。 What do your datatype supposed to return on MyData "foo"
? 您的数据类型应该在MyData "foo"
上返回什么? an error
? 一个error
?
Second, there is the part of haskell philosophy: do everything explicitly. 第二,haskell哲学的一部分:明确地做所有事情。 No typecasts, no Foo foo = 1
which calls foo(const int&)
like in C++. 没有类型转换,没有Foo foo = 1
像C ++中那样调用foo(const int&)
。 And that is a good part. 这是一个很好的部分。
PS: if you get the values from input, just write yourself a proper parser (not just a Read
instance - it crushes thread on failure). PS:如果您从输入中获取值,则只需为自己编写一个适当的解析器即可(不只是Read
实例,它会在失败时破坏线程)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.