Haskell:如何类型转换 [英] Haskell: How to type cast
问题描述
C#:
static int F(object x)
{
return x is string? 1:2;
}
Haskell?
棘手位对我来说,Haskell没有根类型对象
编辑:我不在乎转换为字符串。我想知道如何类型转换(例如查看对象是客户还是订单。
$ b $在Haskell中,允许转换为字符串的所有类型都实例化 Show
typeclass,它提供 / p> show :: Show a => a - > String
$所以你的整个代码只是
fx = show x
或
f = show
使用相同的泛型类型
f :: Show a => a - > String
(对于可以转换为字符串的所有类型a
,取此类型的值并返回字符串)。
请注意,你不必像C#中那样进行显式的运行时类型检查;通用模板在编译时解析。你不需要一个多态的根类型 - 像C#中的转型实际上会有些复杂,并且违背语言的概念。
请注意,在编译时检查兼容性:
- Working
f 1
fHallo
f(1,2)
f [1,2,3]
- 不工作
f(\x - > x + 1)
b $ b响应您编辑的问题:
如前所述,Haskell不允许任意转换非常非常不安全的代码)。因为Haskell不是面向对象的,没有需要任何转换的继承关系。没有简单的没有无意义的
object
需要运行时检查/转换的值。为了表示替代方案,你必须定义一个联合类型,一个类型类或使用Either
类型。
在什么情况下,您遇到的对象是
Customer
或Order
?该类型的值只是无意义。请再次澄清。
对于您的记录器示例:
您需要一个类型类:class Loggable a其中
writeToLog :: a - > IO()
C#:
static int F(object x) { return x is string ? 1 : 2; }
Haskell? The tricky bit seems to me that Haskell does not have a root type object.
Edited: I do not care about converting to string. I want to know how to typecast (for example to see if an object is a Customer or an Order.
解决方案In Haskell, all types that allow a conversion to a string instantiate the
Show
typeclass which providesshow :: Show a => a -> String
So your whole code is nothing but
f x = show x
or
f = show
with the same generic type
f :: Show a => a -> String
(Forall typesa
that are conversible to a string, take a value of this type and return a string).Note that you don't have to do an explicit, run-time type-check like in C#; the generic template is resolved at compile-time. You don't need a polymorphic root type - A cast like in C# would in fact be somewhat complicated and against the language's conception. Instead of allowing arbitrary casts between types, it defined typeclasses for certain meaningful conversions.
Note that compatibility is checked at compile-time:
-- Working f 1 f "Hallo" f (1, 2) f [1, 2, 3] -- Not working f (\x -> x + 1)
In response to your edited question:
As I said before, arbitrary conversions aren't allowed in Haskell (without very very unsafe code). And since Haskell is not object-oriented, there is no inheritance relationship that required any cast. There simply aren't meaningless
object
values that needed runtime-checking/casting. For expressing alternatives, you'll have to define a union type, a typeclass or use theEither
type.In what case do you encounter an object that is a
Customer
or anOrder
? A value of that type is simply nonsensical. Please clarify again.As to your logger example: You'll need a typeclass:
class Loggable a where writeToLog :: a -> IO ()
这篇关于Haskell:如何类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!