如何输入演员表 [英] How to type cast
问题描述
C#:
static int F(object x)
{
return x is string ? 1 : 2;
}
Haskell吗?
在我看来,Haskell没有根类型 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.
推荐答案
在Haskell中,所有允许转换为字符串的类型都实例化 Show
类型类,该类型类提供了
In Haskell, all types that allow a conversion to a string instantiate the Show
typeclass which provides
show :: Show a => a -> String
所以您的整个代码不过是
So your whole code is nothing but
f x = show x
或
f = show
::显示一个=> a->字符串(所有可转换为字符串的类型 a
,取该类型的值并返回
with the same generic type f :: Show a => a -> String
(Forall types a
that are conversible to a string, take a value of this type and return a string).
请注意,您不必像C#中那样进行显式的运行时类型检查;通用模板是在编译时解析的。您不需要多态的根类型-实际上,像C#这样的类型转换会有些复杂,并且会违反l痛苦的概念。
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)
针对您已编辑的问题:
正如我之前说过的,Haskell不允许任意转换(无非常非常不安全的代码)。而且由于Haskell不是面向对象的,因此不存在需要任何强制转换的继承关系。根本就没有没有意义的 object
值需要运行时检查/广播。为了表达替代方案,您必须定义一个联合类型,类型类或使用 Ething
类型。
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 the Either
type.
在哪种情况下,您遇到的对象是 Customer
还是 Order
?该类型的值简直是荒谬的。请再次说明。
In what case do you encounter an object that is a Customer
or an Order
? 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 ()
这篇关于如何输入演员表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!