Type detection: Difference between revisions

m (Added tester function to Python)
Line 515:
The value {1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5} is of type table
The value `function: 00C6C4A8` is of type function</pre>
 
=={{header|Nim}}==
As Nim is a statically typed language, there is no way to detect the type at runtime. But it is possible to write a procedure which writes text in ways depending on the type of a parameter.
 
===Using a generic procedure===
All is done at compile time. The generated code depends on the type of the parameter. We accept here any type, but only provide code to display text from a string and from a file and we emit an error for the other types.
<lang Nim>proc writeText[T](source: T) =
when T is string:
echo source
elif T is File:
echo source.readAll()
else:
echo "Unable to write text for type “", T, "”."
 
writeText("Hello world!")
writeText(stdin)
writeText(3) # Emit an error.</lang>
 
===Using variant objects===
We define a type “Source” which contains a discriminator (tag) which is used to define branches. The code to display the text contains a test on the tag. The only types allowed are those for which a tag value exists. Here, we defined two possible values: “kString” and “kFile”. The “type detection” is done at runtime, but these are not actual types but tag values.
<lang Nim>type Kind = enum kString, kFile
 
type Source = object
case kind: Kind
of kString: str: string
of kFile: file: File
 
proc writeText(source: Source) =
case source.kind
of kString: echo source.str
of kFile: echo source.file.readAll()
 
let s1 = Source(kind: kString, str: "Hello world!")
let s2 = Source(kind: kFile, file: stdin)
 
s1.writeText()
s2.writeText()</lang>
 
=={{header|Perl}}==
Anonymous user