View Single Post
  #2 (permalink)  
Old May 29th, 2008, 09:45 AM
ciderpunx ciderpunx is offline
Friend of Wrox
 
Join Date: Dec 2003
Posts: 488
Thanks: 0
Thanked 3 Times in 3 Posts
Default

I'd define a data type as something like "a datum or set of data with values having predefined characteristics" for example floating point, integer numbers, structs or classes.

I'll try and explain loosely typed by looking first at strongly typed. Strongly typed generally means that there's some kind of checking of types to make sure that you don't trip over yourself and use the wrong type. In a mathematical function it would be better for it to blow up when you pass it a string than for it to try and add a string to an integer. There's no reason why you can't pass an object (i.e. instance of a class) to a function but in a strongly typed language the interpreter or compiler will make sure that you've passed an instance of the correct class and die if you haven't.

Here's some code in java - a strongly-typed language
Code:
public class type{
  private int x;

  public type(int y) {
    this.x=y;
  }

  public int squared () {
    return (this.x * this.x);
  }

  public static void main(String argv[]) {
    type t = new type(4);
    System.out.println(t.squared());
  }
}
This compiles happily and prints 16 to the screen. If we change:
Code:
type t = new type(4);
to:
Code:
type t = new type("House");
The the java compiler blows up like this:
Code:
charlie@charlie:~/src/java$ javac type.java 
type.java:13: cannot find symbol
symbol  : constructor type(java.lang.String)
location: class type
        type t = new type("House");
                 ^
1 error
charlie@charlie:~/src/java$
This is considered a good thing by some programmers who are afraid of their types getting in a muddle.

In Perl, a loosely typed language we could write something similar (I use a function rather than a class for conciseness).
Code:
#!/usr/bin/perl

sub squared($) {
  my $x=shift;
  return $x+$x;
}

print squared(4) . "\n" . squared("House") . "\n";
Perl silently evaluates the String as 0 and prints
Code:
8
0
See also http://blog.jeremymartin.name/2008/0...typing-in.html

Cheers


--
Charlie Harvey's website - linux, perl, java, anarchism and punk rock: http://charlieharvey.org.uk
Reply With Quote