Type detection

From Rosetta Code
Revision as of 18:22, 9 October 2015 by rosettacode>Craigd (→‎{{header|zkl}}: added how to use)
This page is scheduled for deletion after 09-Oct-2015. - See discussion page'
Type detection is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

This draft task needs a purpose, a description and some way to tell whether examples satisfy or do not satisfy it.

Task Description

Show a function/procedure that, when given an object of type Any (or just unknown type), performs a common task.

For example: you want to process a block of text. The function takes a parameter that is, or somehow describes, the block of text (and provides a method or call to access and return that block of text). The task is then to show how function gets the text from the parameter (but not show the text processing).

JavaScript

[1]

console.log(typeof('foo')); // Returns string
console.log(typeof(12345)); // Returns number

OASYS Assembler

<lang oasys_oaa>

The following method checks if a global variable or property is an
object type. Does not work with locals and arguments.

[&OBJ#,^]

 ,^<,^<<    ; Remember old value
 ,^<*>      ; Create new object
 ,^<<DES    ; Destroy the object
 ,^<<EX     ; Check if variable has been cleared
 />1RF      ; It is clear
 :>0RF      ; It is not clear

</lang>

PHP

[2]

echo gettype('foo'); // Returns string
echo gettype(12345); // Returns integer

Specific tester functions

zkl

<lang zkl>fcn processText(data_or_fileName){ // unknown

  if (data_or_fileName.isType(String)) // == .isType("")
     data_or_fileName=File(data_or_fileName,"rb").read(); //-->Data
  text:=data_or_fileName.text;  //-->String
  doTheActualTextProcessing(text);

} fcn doTheActualTextProcessing(text){ println(text) }</lang> If an int is passed in, (123).text --> "123", other objects might throw an exception.

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

Output:
this is foo.txt

This is some text
this is more text