Type detection: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 21: Line 21:
=={{header|ATS}}==
=={{header|ATS}}==
===Using garbage collection and '''datatype'''===
===Using garbage collection and '''datatype'''===
<lang ats>#include "share/atspre_staload.hats"
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats"


datatype source_t =
datatype source_t =
Line 53: Line 53:
print_text (source_t_string "This\nis a\ntext.\n");
print_text (source_t_string "This\nis a\ntext.\n");
print_text (source_t_FILEref f)
print_text (source_t_FILEref f)
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 98: Line 98:
In this implementation, '''print_text''' consumes its argument; the argument’s value cannot be used again. However, the object wrapped in the '''source_vt''' might be reusable.
In this implementation, '''print_text''' consumes its argument; the argument’s value cannot be used again. However, the object wrapped in the '''source_vt''' might be reusable.


<lang ats>#include "share/atspre_staload.hats"
<syntaxhighlight lang="ats">#include "share/atspre_staload.hats"


dataviewtype source_vt =
dataviewtype source_vt =
Line 132: Line 132:
| ~ Some_vt f => print_text (source_vt_FILEref f)
| ~ Some_vt f => print_text (source_vt_FILEref f)
| ~ None_vt () => fprintln! (stderr_ref, "Failed to open the file.")
| ~ None_vt () => fprintln! (stderr_ref, "Failed to open the file.")
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
$ patscc -DATS_MEMALLOC_LIBC type_detection-postiats-2.dats && ./a.out
$ patscc -DATS_MEMALLOC_LIBC type_detection-postiats-2.dats && ./a.out
Line 175: Line 175:


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: TAWK -f TYPE_DETECTION.AWK
# syntax: TAWK -f TYPE_DETECTION.AWK
# uses Thompson Automation's TAWK 5.0c
# uses Thompson Automation's TAWK 5.0c
Line 190: Line 190:
exit(0)
exit(0)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 205: Line 205:
=={{header|C}}==
=={{header|C}}==
The closest C comes to meeting this task, short of building it into the compiler or accessing memory segments via pointers, which is not guaranteed to be portable, is the ctype.h header file. It is part of the C Standard Library and provides 11 methods for detecting the type of a character, out of which the following 7 called in the wrapper function below can be called to be unique. The function accepts a string, but it actually checks the first character. An if ladder is used instead of if-else so that all function calls which return a non-zero value for the character are satisfied and the information is printed.
The closest C comes to meeting this task, short of building it into the compiler or accessing memory segments via pointers, which is not guaranteed to be portable, is the ctype.h header file. It is part of the C Standard Library and provides 11 methods for detecting the type of a character, out of which the following 7 called in the wrapper function below can be called to be unique. The function accepts a string, but it actually checks the first character. An if ladder is used instead of if-else so that all function calls which return a non-zero value for the character are satisfied and the information is printed.
<syntaxhighlight lang="c">
<lang C>
#include<stdio.h>
#include<stdio.h>
#include<ctype.h>
#include<ctype.h>
Line 238: Line 238:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
Output, shown for multiple inputs, as well as single ones:
Output, shown for multiple inputs, as well as single ones:
<pre>
<pre>
Line 286: Line 286:


===Dispatch by ''tagged union''===
===Dispatch by ''tagged union''===
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdbool.h>
#include <stdbool.h>
#include <assert.h>
#include <assert.h>
Line 339: Line 339:
source.value.input_file = fopen ("type_detection-c.c", "r");
source.value.input_file = fopen ("type_detection-c.c", "r");
print_text (source);
print_text (source);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
$ cc type_detection-c.c && ./a.out
$ cc type_detection-c.c && ./a.out
Line 401: Line 401:


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace TypeDetection {
namespace TypeDetection {
Line 427: Line 427:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>The type of '5' is System.Int32
<pre>The type of '5' is System.Int32
Line 441: Line 441:
=={{header|C++}}==
=={{header|C++}}==
{{trans|D}}
{{trans|D}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


template <typename T>
template <typename T>
Line 461: Line 461:
std::cout << typeString(S{}) << '\n';
std::cout << typeString(S{}) << '\n';
std::cout << typeString(nullptr) << '\n';
std::cout << typeString(nullptr) << '\n';
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>int
<pre>int
Line 474: Line 474:


=={{header|Crystal}}==
=={{header|Crystal}}==
<lang Ruby>def print_type(x)
<syntaxhighlight lang="ruby">def print_type(x)
puts "Compile-time type of #{x} is #{typeof(x)}"
puts "Compile-time type of #{x} is #{typeof(x)}"
puts " Actual runtime type is #{x.class}" if x.class != typeof(x)
puts " Actual runtime type is #{x.class}" if x.class != typeof(x)
Line 490: Line 490:
print_type({a: 1, b: 2})
print_type({a: 1, b: 2})
print_type ->(x : Int32){ x+2 > 0 }
print_type ->(x : Int32){ x+2 > 0 }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>Compile-time type of 123 is Int32
<pre>Compile-time type of 123 is Int32
Line 507: Line 507:


=={{header|D}}==
=={{header|D}}==
<lang D>import std.stdio;
<syntaxhighlight lang="d">import std.stdio;


auto typeString(T)(T _) {
auto typeString(T)(T _) {
Line 526: Line 526:
writeln(typeString(S()));
writeln(typeString(S()));
writeln(typeString(null));
writeln(typeString(null));
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 540: Line 540:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>
<syntaxhighlight lang="fsharp">
printfn "%A" (3.14.GetType())
printfn "%A" (3.14.GetType())
let inline fN g=g.GetType()|>string
let inline fN g=g.GetType()|>string
printfn "%s" (fN "Nigel")
printfn "%s" (fN "Nigel")
printfn "%s" (fN 23)
printfn "%s" (fN 23)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 554: Line 554:
=={{header|Factor}}==
=={{header|Factor}}==
Using dynamic dispatch:
Using dynamic dispatch:
<lang>USING: arrays formatting io kernel math prettyprint sequences
<syntaxhighlight lang="text">USING: arrays formatting io kernel math prettyprint sequences
strings ;
strings ;
IN: rosetta-code.type-detection
IN: rosetta-code.type-detection
Line 569: Line 569:
{ 1 2 3 4 5 } myprint
{ 1 2 3 4 5 } myprint
123 myprint
123 myprint
3.1415 myprint</lang>
3.1415 myprint</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 591: Line 591:
Below I use ‘class(*)’. The ‘print_text’ subroutine is used to print a string, an array of strings, and an input file.
Below I use ‘class(*)’. The ‘print_text’ subroutine is used to print a string, an array of strings, and an input file.


<lang fortran>program input_type_detection_demo
<syntaxhighlight lang="fortran">program input_type_detection_demo
implicit none
implicit none


Line 652: Line 652:
end subroutine print_text
end subroutine print_text


end program input_type_detection_demo</lang>
end program input_type_detection_demo</syntaxhighlight>


{{out}}
{{out}}
Line 735: Line 735:
(To use this mechanism in a library, one would want to use modules. Nevertheless, the program below illustrates the principle more simply.)
(To use this mechanism in a library, one would want to use modules. Nevertheless, the program below illustrates the principle more simply.)


<lang fortran>program type_detection_demo
<syntaxhighlight lang="fortran">program type_detection_demo


implicit none
implicit none
Line 786: Line 786:
end subroutine print_text_file_unit
end subroutine print_text_file_unit


end program type_detection_demo</lang>
end program type_detection_demo</syntaxhighlight>
{{out}}
{{out}}
$ gfortran type_detection-fortran-2.f90 && ./a.out
$ gfortran type_detection-fortran-2.f90 && ./a.out
Line 854: Line 854:
=={{header|Go}}==
=={{header|Go}}==
Note that Go doesn't really have a character type. A single quoted character (such as 'd') is by default a ''rune'' (or 32 bit integer) literal representing its Unicode code-point.
Note that Go doesn't really have a character type. A single quoted character (such as 'd') is by default a ''rune'' (or 32 bit integer) literal representing its Unicode code-point.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 874: Line 874:
showType(value)
showType(value)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 889: Line 889:
{{trans|Icon}}
{{trans|Icon}}


<lang goaldi>procedure main() {
<syntaxhighlight lang="goaldi">procedure main() {
print_text("This\nis a\ntext.\n")
print_text("This\nis a\ntext.\n")
print_text(file("type_detection-goaldi.gd"))
print_text(file("type_detection-goaldi.gd"))
Line 899: Line 899:
file : while write(read(source))
file : while write(read(source))
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 924: Line 924:
See also [[#ObjectIcon|ObjectIcon]] and [[#Goaldi|Goaldi]].
See also [[#ObjectIcon|ObjectIcon]] and [[#Goaldi|Goaldi]].


<lang icon>procedure main()
<syntaxhighlight lang="icon">procedure main()
print_text("This\nis\na text.\n")
print_text("This\nis\na text.\n")
print_text(open("type_detection-icon.icn"))
print_text(open("type_detection-icon.icn"))
Line 934: Line 934:
"file" : while write(read(source))
"file" : while write(read(source))
}
}
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
$ icont -u -s type_detection-icon.icn && ./type_detection-icon
$ icont -u -s type_detection-icon.icn && ./type_detection-icon
Line 956: Line 956:
Presumably this satisfies the task requirements...
Presumably this satisfies the task requirements...


<lang J> echo 'one'
<syntaxhighlight lang="j"> echo 'one'
one
one
echo 1
echo 1
1</lang>
1</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|Kotlin}}
{{trans|Kotlin}}
<lang Java>public class TypeDetection {
<syntaxhighlight lang="java">public class TypeDetection {
private static void showType(Object a) {
private static void showType(Object a) {
if (a instanceof Integer) {
if (a instanceof Integer) {
Line 982: Line 982:
showType(true);
showType(true);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>'5' is an integer
<pre>'5' is an integer
Line 1,028: Line 1,028:
<code>typeof</code> function, and the function <code>isa</code> tests
<code>typeof</code> function, and the function <code>isa</code> tests
whether an object is of that type.
whether an object is of that type.
<syntaxhighlight lang="julia">
<lang Julia>


julia> a = 1
julia> a = 1
Line 1,075: Line 1,075:
true
true


</syntaxhighlight>
</lang>


=={{header|OASYS Assembler}}==
=={{header|OASYS Assembler}}==


<lang oasys_oaa>
<syntaxhighlight lang="oasys_oaa">
; The following method checks if a global variable or property is an
; The following method checks if a global variable or property is an
; object type. Does not work with locals and arguments.
; object type. Does not work with locals and arguments.
Line 1,090: Line 1,090:
/>1RF ; It is clear
/>1RF ; It is clear
:>0RF ; It is not clear
:>0RF ; It is not clear
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6
fun showType(a: Any) = when (a) {
fun showType(a: Any) = when (a) {
is Int -> println("'$a' is an integer")
is Int -> println("'$a' is an integer")
Line 1,106: Line 1,106:
showType('d')
showType('d')
showType(true)
showType(true)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,117: Line 1,117:


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>function writeValue(v)
<syntaxhighlight lang="lua">function writeValue(v)
local t = type(v)
local t = type(v)
if t == "number" then
if t == "number" then
Line 1,157: Line 1,157:
end
end


main()</lang>
main()</syntaxhighlight>
{{out}}
{{out}}
<pre>The value 42 is of type number
<pre>The value 42 is of type number
Line 1,170: Line 1,170:
===Using a generic procedure===
===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.
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) =
<syntaxhighlight lang="nim">proc writeText[T](source: T) =
when T is string:
when T is string:
echo source
echo source
Line 1,180: Line 1,180:
writeText("Hello world!")
writeText("Hello world!")
writeText(stdin)
writeText(stdin)
writeText(3) # Emit an error.</lang>
writeText(3) # Emit an error.</syntaxhighlight>


===Using variant objects===
===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.
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
<syntaxhighlight lang="nim">type Kind = enum kString, kFile


type Source = object
type Source = object
Line 1,200: Line 1,200:


s1.writeText()
s1.writeText()
s2.writeText()</lang>
s2.writeText()</syntaxhighlight>


=={{header|ObjectIcon}}==
=={{header|ObjectIcon}}==
{{trans|Icon}}
{{trans|Icon}}
<lang objecticon>import io
<syntaxhighlight lang="objecticon">import io


procedure main()
procedure main()
Line 1,216: Line 1,216:
"object" : while write(source.read())
"object" : while write(source.read())
}
}
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
$ oit -s type_detection-oi.icn && ./type_detection-oi
$ oit -s type_detection-oi.icn && ./type_detection-oi
Line 1,240: Line 1,240:
Pascal has a plethora of dialects, and so I have tried to be as close to ''Algorithms + Data Structures = Programs'' (Wirth) style as I could figure out how, when using the Free Pascal Compiler.
Pascal has a plethora of dialects, and so I have tried to be as close to ''Algorithms + Data Structures = Programs'' (Wirth) style as I could figure out how, when using the Free Pascal Compiler.


<lang pascal>program typedetectiondemo (input, output);
<syntaxhighlight lang="pascal">program typedetectiondemo (input, output);
type
type
sourcetype = record case kind : (builtintext, filetext) of
sourcetype = record case kind : (builtintext, filetext) of
Line 1,281: Line 1,281:
printtext (source)
printtext (source)
end
end
end.</lang>
end.</syntaxhighlight>


{{out}}
{{out}}
Line 1,333: Line 1,333:
The function <code>ref</code> takes a reference to a variable, via '\', and returns the type. Some of the more common are shown here.
The function <code>ref</code> takes a reference to a variable, via '\', and returns the type. Some of the more common are shown here.
In the cases where the value in question is already a reference (<code>$regex</code> and <code>$subref</code>) the '\' is not used.
In the cases where the value in question is already a reference (<code>$regex</code> and <code>$subref</code>) the '\' is not used.
<lang perl>$scalar = 1;
<syntaxhighlight lang="perl">$scalar = 1;
@array = (1, 2);
@array = (1, 2);
%hash = ('a' => 1);
%hash = ('a' => 1);
Line 1,347: Line 1,347:
printf $fmt, '$regex', ref( $regex);
printf $fmt, '$regex', ref( $regex);
printf $fmt, '$reference', ref(\$reference);
printf $fmt, '$reference', ref(\$reference);
printf $fmt, '$subref', ref( $subref);</lang>
printf $fmt, '$subref', ref( $subref);</syntaxhighlight>
{{out}}
{{out}}
<pre>$scalar is type: SCALAR
<pre>$scalar is type: SCALAR
Line 1,359: Line 1,359:
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
Phix builtin type tests are: integer(), atom(), string(), sequence(), and object(). The latter returns true unless arg is unassigned, also notice that showtype never even attempts to set t to "object", since it is guaranteed to be one of the other four.
Phix builtin type tests are: integer(), atom(), string(), sequence(), and object(). The latter returns true unless arg is unassigned, also notice that showtype never even attempts to set t to "object", since it is guaranteed to be one of the other four.
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">showtype</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">showtype</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">o</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">"integer"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"atom"</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)?</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">o</span><span style="color: #0000FF;">)?</span><span style="color: #008000;">"integer"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"atom"</span><span style="color: #0000FF;">)</span>
Line 1,370: Line 1,370:
<span style="color: #000000;">showtype</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"string"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">showtype</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"string"</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">showtype</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7.5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"string"</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">showtype</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">7.5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"string"</span><span style="color: #0000FF;">})</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,413: Line 1,413:
=={{header|PowerShell}}==
=={{header|PowerShell}}==
In PowerShell everything is an object and all objects have the GetType() method:
In PowerShell everything is an object and all objects have the GetType() method:
<syntaxhighlight lang="powershell">
<lang PowerShell>
[string]$str = "123"
[string]$str = "123"
$str.GetType()
$str.GetType()
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,423: Line 1,423:
True True String System.Object
True True String System.Object
</pre>
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
[int]$int = $str -as [int]
[int]$int = $str -as [int]
$int.GetType()
$int.GetType()
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,462: Line 1,462:
http://docs.racket-lang.org/ts-reference/type-ref.html
http://docs.racket-lang.org/ts-reference/type-ref.html


<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket


(require racket/undefined)
(require racket/undefined)
Line 1,595: Line 1,595:
(td ,(string-join (->type-names v) ", "))))
(td ,(string-join (->type-names v) ", "))))
test-values)))))
test-values)))))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,689: Line 1,689:
This is really a very broad and kind of hand-wavey overview of Raku types. For much more in-depth coverage see: https://docs.raku.org/type.html
This is really a very broad and kind of hand-wavey overview of Raku types. For much more in-depth coverage see: https://docs.raku.org/type.html


<lang perl6>sub type ($t) { say $t.raku, "\tis type: ", $t.WHAT }
<syntaxhighlight lang="raku" line>sub type ($t) { say $t.raku, "\tis type: ", $t.WHAT }


# some content types
# some content types
Line 1,705: Line 1,705:
my my-type $object;
my my-type $object;


$object.&type;</lang>
$object.&type;</syntaxhighlight>


{{out}}
{{out}}
Line 1,737: Line 1,737:
<br>strings can be classified by having certain characteristics, &nbsp; or in other words, ''types''.
<br>strings can be classified by having certain characteristics, &nbsp; or in other words, ''types''.
<br>Characteristics of these &nbsp; ''types'' &nbsp; can overlap.
<br>Characteristics of these &nbsp; ''types'' &nbsp; can overlap.
<lang rexx>/*REXX program displays what "type" a variable is (based on the variable's value). */
<syntaxhighlight lang="rexx">/*REXX program displays what "type" a variable is (based on the variable's value). */
signal on noValue /*trap for undefined REXX variables. */
signal on noValue /*trap for undefined REXX variables. */
y= 1938 ; call showType y /*╔═══════════════════════════════════╗*/
y= 1938 ; call showType y /*╔═══════════════════════════════════╗*/
Line 1,780: Line 1,780:
if datatype(x, 'S') then say @ "a REXX symbol."
if datatype(x, 'S') then say @ "a REXX symbol."
say copies('▒', 50) /*a fence that is used as a separator. */
say copies('▒', 50) /*a fence that is used as a separator. */
return</lang>
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default data:}}
{{out|output|text=&nbsp; when using the internal default data:}}
<pre>
<pre>
Line 1,873: Line 1,873:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Type detection
# Project : Type detection


Line 1,879: Line 1,879:
see "7.5 -> " + type(7.5) + nl
see "7.5 -> " + type(7.5) + nl
see "d -> " + type('d') + nl
see "d -> " + type('d') + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,896: Line 1,896:
The compiler will require that all possible values are handled, even if it's as simple as a fallthrough <code>_ => unreachable!()</code> which causes the program to die in a memory-safe way.
The compiler will require that all possible values are handled, even if it's as simple as a fallthrough <code>_ => unreachable!()</code> which causes the program to die in a memory-safe way.


<lang rust>enum ExpectedTypes {
<syntaxhighlight lang="rust">enum ExpectedTypes {
Int(i64),
Int(i64),
UInt(u64),
UInt(u64),
Line 1,920: Line 1,920:
}
}
}
}
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 1,937: Line 1,937:
As Rust allows you to implement your own traits on other people's types, this can be used to implement type detection.
As Rust allows you to implement your own traits on other people's types, this can be used to implement type detection.


<lang rust>use std::error::Error;
<syntaxhighlight lang="rust">use std::error::Error;
use std::fs::File;
use std::fs::File;
use std::io::{self,prelude::*};
use std::io::{self,prelude::*};
Line 1,994: Line 1,994:


Ok(())
Ok(())
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 2,010: Line 2,010:
Finally, while it's more limited than it appears, Rust does have some small degree of support for type introspection.
Finally, while it's more limited than it appears, Rust does have some small degree of support for type introspection.


<lang rust>use std::any::Any;
<syntaxhighlight lang="rust">use std::any::Any;


pub fn is_string(thing: &dyn Any) {
pub fn is_string(thing: &dyn Any) {
Line 2,023: Line 2,023:
is_string(&"Hello, World!");
is_string(&"Hello, World!");
is_string(&5u16);
is_string(&5u16);
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 2,030: Line 2,030:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>object TypeDetection extends App {
<syntaxhighlight lang="scala">object TypeDetection extends App {
def showType(a: Any) = a match {
def showType(a: Any) = a match {
case a: Int => println(s"'$a' is an integer")
case a: Int => println(s"'$a' is an integer")
Line 2,045: Line 2,045:
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")
println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]")


}</lang>
}</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (print-text source)
<syntaxhighlight lang="scheme">(define (print-text source)
(cond ((string? source)
(cond ((string? source)
;; The source is a string.
;; The source is a string.
Line 2,069: Line 2,069:
(print-text '("Print\n" "a list\n" "of strings.\n"))
(print-text '("Print\n" "a list\n" "of strings.\n"))


(call-with-input-file "type_detection-scheme.scm" print-text)</lang>
(call-with-input-file "type_detection-scheme.scm" print-text)</syntaxhighlight>


{{out}}
{{out}}
Line 2,104: Line 2,104:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Just send class to any object and ask the class for its name...
Just send class to any object and ask the class for its name...
<lang smalltalk>typeOf := [:anyObject |
<syntaxhighlight lang="smalltalk">typeOf := [:anyObject |
e'arg is of type {anyObject class name} and prints itself as: "{anyObject printString}"' printCR
e'arg is of type {anyObject class name} and prints itself as: "{anyObject printString}"' printCR
].
].
Line 2,127: Line 2,127:
typeOf value: (SmallInteger >> #+).
typeOf value: (SmallInteger >> #+).
[ 1 / 0 ] on:Error do:[:ex | typeOf value: ex ]. "catch the exception"
[ 1 / 0 ] on:Error do:[:ex | typeOf value: ex ]. "catch the exception"
[ 1 fooBar ] on:Error do:[:ex | typeOf value: ex ].</lang>
[ 1 fooBar ] on:Error do:[:ex | typeOf value: ex ].</syntaxhighlight>
{{out}}
{{out}}
<pre>arg is of type SmallInteger and prints itself as: "1234"
<pre>arg is of type SmallInteger and prints itself as: "1234"
Line 2,154: Line 2,154:
=={{header|VBA}}==
=={{header|VBA}}==
VBA has a built-in function TypeName (VarType returns a number), which can also recognize arrays.
VBA has a built-in function TypeName (VarType returns a number), which can also recognize arrays.
<lang vb>Public Sub main()
<syntaxhighlight lang="vb">Public Sub main()
Dim c(1) As Currency
Dim c(1) As Currency
Dim d(1) As Double
Dim d(1) As Double
Line 2,189: Line 2,189:
Debug.Print TypeName(CStr(1))
Debug.Print TypeName(CStr(1))
Debug.Print TypeName(Worksheets(1))
Debug.Print TypeName(Worksheets(1))
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>Application
<pre>Application
Boolean
Boolean
Line 2,216: Line 2,216:
=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Module TypeDetection
<syntaxhighlight lang="vbnet">Module TypeDetection


Sub Main()
Sub Main()
Line 2,230: Line 2,230:


End Module
End Module
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,241: Line 2,241:


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>fn show_type<T>(a T) {
<syntaxhighlight lang="vlang">fn show_type<T>(a T) {
println('The type of $a is ${typeof(a).name}')
println('The type of $a is ${typeof(a).name}')
}
}
Line 2,251: Line 2,251:
show_type(`s`)
show_type(`s`)
show_type([0x32,0x22])
show_type([0x32,0x22])
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,264: Line 2,264:
=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-fmt}}
<lang ecmascript>import "./fmt" for Fmt
<syntaxhighlight lang="ecmascript">import "./fmt" for Fmt


var showType = Fn.new { |obj|
var showType = Fn.new { |obj|
Line 2,271: Line 2,271:


var a = [4, 3.728, [1, 2], { 1: "first" }, true, null, 1..6, "Rosetta"]
var a = [4, 3.728, [1, 2], { 1: "first" }, true, null, 1..6, "Rosetta"]
a.each { |e| showType.call(e) }</lang>
a.each { |e| showType.call(e) }</syntaxhighlight>


{{out}}
{{out}}
Line 2,286: Line 2,286:


=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
<lang z80>PrintChar equ &BB5A ;Amstrad CPC BIOS Call
<syntaxhighlight lang="z80">PrintChar equ &BB5A ;Amstrad CPC BIOS Call


org &8000
org &8000
Line 2,386: Line 2,386:
byte 1,&46
byte 1,&46
TestBCD:
TestBCD:
byte 2,&99</lang>
byte 2,&99</syntaxhighlight>


{{out}}
{{out}}
Line 2,398: Line 2,398:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn processText(data_or_fileName){ // unknown
<syntaxhighlight lang="zkl">fcn processText(data_or_fileName){ // unknown
if (data_or_fileName.isType(String)) // == .isType("")
if (data_or_fileName.isType(String)) // == .isType("")
data_or_fileName=File(data_or_fileName,"rb").read(); //-->Data
data_or_fileName=File(data_or_fileName,"rb").read(); //-->Data
Line 2,404: Line 2,404:
doTheActualTextProcessing(text);
doTheActualTextProcessing(text);
}
}
fcn doTheActualTextProcessing(text){ println(text) }</lang>
fcn doTheActualTextProcessing(text){ println(text) }</syntaxhighlight>
If an int is passed in, (123).text --> "123", other objects might throw an exception.
If an int is passed in, (123).text --> "123", other objects might throw an exception.


How to use:
How to use:
<lang zkl>processText("foo.txt");
<syntaxhighlight lang="zkl">processText("foo.txt");
processText(Data(Void,"This is some text"));
processText(Data(Void,"This is some text"));
// fake up a class that holds a string:
// fake up a class that holds a string:
cs:=class{ var text }; cs.text="this is more text";
cs:=class{ var text }; cs.text="this is more text";
processText(cs);</lang>
processText(cs);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>