Types by dfhdhdhdhjr

VIEWS: 3 PAGES: 29

									Types

  CS351 – Programming Paradigms




           Mark Hennessy CS351 Dept Computer
                  Science NUI Maynooth         1
Data Types

     Nearly all programming languages
      include the notion of a type for
      expressions and objects*.
 1.   a + b allows a and b to be of some
      numeric type e.g int, float etc.
 2.   Types limit the set of operations that
      can be performed on some object*.


                 Mark Hennessy CS351 Dept Computer
                        Science NUI Maynooth         2
Type Systems

    A type system consists of the following:
      1.   A mechanism to define types and associate
           them with certain language constructs.
      2.   A set of rules for type equivalence, type
           compatibility and type inference.
    ``Types’’ of types: constants, variables,
     records, arrays, parameters etc.



                   Mark Hennessy CS351 Dept Computer
                          Science NUI Maynooth         3
Type Systems cont…

  Type Equivalence: rules determine when
   two values are the same type.
  Type Compatibility: rules to determine if
   a value of a certain type can be used in a
   given context, e.g in an l-value
   assignment.
  Type Inference: These rules define the
   type based upon the types of its
   constituent parts.
               Mark Hennessy CS351 Dept Computer
                      Science NUI Maynooth         4
Type Checking
  Type checking is a process of ensuring that a program
   obeys the languages’ type rules.
  A language is strongly typed if it prohibits the
   application of any illegal operation.
  A language is statically typed is it is strongly typed and
   type checking is performed at compile time.
  Ada is strongly typed, Pascal and C less so.
  Dynamic type checking is a form of binging types to
   variables only when they are seen at runtime.
  Most scripting languages and those with dynamic
   scope use dynamic type checking.

                    Mark Hennessy CS351 Dept Computer
                           Science NUI Maynooth                 5
Polymorphism

  No, not in the OO sense!
  It allows a single body of code to work
   with multiple types.
  Examples:
  The math operators +,-,*,/ work on ints,
   floats, shorts, doubles in Java!
  In C++ we can overload those operators
   to work on classes!
               Mark Hennessy CS351 Dept Computer
                      Science NUI Maynooth         6
Classification of Types

    Nearly all languages will have simple
     built in types.
      1.   Boolean type, a 1-byte representing T or F.
      2.   Characters, 1-byte representing 256 ASCII
           characters. Old skool, there are now supports
           for ISO 10646 which supports charaters for all
           human ( and non-human! ) characters.
      3.   Numeric types: generally integer types which
           can be signed or unsigned (C,C++). Floating
           point types correspond to the IEEE 754
           floating point number standard.

                   Mark Hennessy CS351 Dept Computer
                          Science NUI Maynooth              7
Enumerated Types

  Built-in types are known as discrete types as
   they all in the countable domain.
  It is possible to extend the built in types
   through the use of enumeration.

 enum weekdays = { mon, tues, wed, thurs, fri };
  
 typedef int weekday;
 const weekday mon = 0, tues = 1, wed = 2, thurs = 3,
                fri = 4;


                     Mark Hennessy CS351 Dept Computer
                            Science NUI Maynooth         8
Enumeration in Java?

    Old Way:
 public static final int mon = 0;
 public static final int tues = 1;
 …
 int day = weekdays.mon;

    New Way:
 enum weekdays { mon(0), tues(1) … fri(3);
     private final int day;
     weekdays(int d) day = d;
     public int day() return day;
 }
 int day = weekdays.mon.day();


                          Mark Hennessy CS351 Dept Computer
                                 Science NUI Maynooth         9
Composite Types

     Not built-in but not explicitly user defined.
 1.   Records or Structures.
 2.   Arrays.
 3.   Sets.
 4.   Pointers.
 5.   Lists.
 6.   Files.


                   Mark Hennessy CS351 Dept Computer
                          Science NUI Maynooth         10
Implementing Type Checking

  Every definition of some variable must
   include a type definition.
  For builtin types it is quite easy to
   determine the type without knowing
   where the declaration took place?
  What does the C/C++ keyword sizeof
   do?
  E.g int a = 5; std::cout<<sizeof(a);

               Mark Hennessy CS351 Dept Computer
                      Science NUI Maynooth         11
User defined Type Equivalence
   Do we compare user-defined types by their internal structure or
    via their names?
 Given some user-defined type
 type foo = record
    a:int
    b:int
 end;

 type foo2 = record
    b:int
    a:int
 end;

 foo one; foo2 two;
 Print one == two;



                       Mark Hennessy CS351 Dept Computer
                              Science NUI Maynooth                    12
What about?
 type student = record
    name, address = string
    age :int
 end;

 type school = record
    name, address = string
    Num_students: int
                                 Is this an error?
 end;
                                 No!!
 x: student;                     But we surely didn’t mean to assign
 y: school;                      student the value of school.
                                 Structural equivalence is not a good
 Print x == y;
                                 way of type checking.

                      Mark Hennessy CS351 Dept Computer
                             Science NUI Maynooth                       13
Name Equivalence

    This is based on the premise that is we have
     declared two different types then they are
     more then likely different types!

 x: student will be linked to the first record type
    and
 y: school will be linked to the second record type.
 Hence the Print x == y will result in an error.
  At what point, compile or run-time?

                  Mark Hennessy CS351 Dept Computer
                         Science NUI Maynooth         14
Type Conversion

  In a language with static typing, there are
   many contexts in which a specific type
   are expected.
  Consider:

 a = square (5);
  What can we assume about the expression above?
  Specifically in relation to the l- and r-values?



                  Mark Hennessy CS351 Dept Computer
                         Science NUI Maynooth         15
Type Conversion cont…
     Sometimes we need to perform type casting to
      change the type of data contained in one variable
      and assign it to another. There are ~ 2 cases:
 1.   The types are structurally equivalent but the
      language uses name-equaivalences. This is very
      easy, recall our earlier example:
      x: student; y: school; x.age = y.num_students;
 2.   The types have different representations ``under the
      hood’’. E.g, any int can be written as floating point
      number.
      int a = 5; float f = (float) a;

                           Mark Hennessy CS351 Dept Computer
                                  Science NUI Maynooth         16
Type Conversion cont…

    In C++ there are builtin functions to
     perform the casts:

 int a = 5;
 double a = static_cast<double>(a);

 double b = reinterpret_cast<double>(a);


    What is the difference?
                  Mark Hennessy CS351 Dept Computer
                         Science NUI Maynooth         17
Type Compatibility
    To facilitate the creation of container classes such as Stack,
     Vector etc several languages provide a generic reference type. In
     C\C++ this is void * which can refer to almost anything within a
     program.
    With void *, any l-value can be assigned to a void *.

 void * p = NULL:
 int a; double b;
 p = a; p = b;

    Java has this feature too, the generic ability to point to anything.
     What is it?


                         Mark Hennessy CS351 Dept Computer
                                Science NUI Maynooth                        18
Type Inference

  How do you determine the overall type of
   some expression?
  Easily:

    The result of arithmetic has the same type as its operands.

    The result of any logical statement is a boolean.

    The result of a function is always declared by the user.

    The result of an assignment is the same as the l-value type.

                         Mark Hennessy CS351 Dept Computer
                                Science NUI Maynooth                19
Composite Types
1 – Structures and Unions
    These are an old style way of tying together
     data in a kind of manner like a class.
              struct example
              {
                       char name[2];
                       int number;
              }
  Each of the components is known as a field.
  To access the data, just use a pointer (in C) or
   a ``dot’’ (most other languages).
              example *one; one->number = 7;
              example two; two.number = 8;

                    Mark Hennessy CS351 Dept Computer
                           Science NUI Maynooth         20
2 - Arrays
  One of the most common and important data types.
  The data within an array is typically homogenous.
  Arrays can be thought of as a mapping from an index
   to a particular component.
  This mapping is typically an integer but more recent
   scripting languages allow array indices to be whatever
   we want.
  These are just hash tables in disguise. We will cover
   them again.
  Arrays typically use the ``[ ]’’ brackets to index them.


                    Mark Hennessy CS351 Dept Computer
                           Science NUI Maynooth               21
2 – Arrays cont…

    Some languages allow for a powerful
     feature known as an array slice.

 Eg in python:
 S = “Hello World”
 print S[6:]


    What is the answer?

                     Mark Hennessy CS351 Dept Computer
                            Science NUI Maynooth         22
2 – Arrays cont…

  Array sizes can be fixed when the array
   is declared. Eg. int a[] = new int[5];
  This memory can then be allocated at
   compile time.
  Arrays can also be allocated at run-time:
 int a [] = new int[Integer.parseInt(args[0])];
  Arrays can even have their length
   increased: String s = “hel”; s = s+”lo”;
                Mark Hennessy CS351 Dept Computer
                       Science NUI Maynooth         23
2 - Arrays cont…
     When an array is declared affects how memory for
      the array is allocated.
 1.   Global lifetime, static shape: If the shape is known at compile time and the
      array is global (static) then the array can exist throughout the lifetime of
      the program.
 2.   Local lifetime, static shape: If the shape is known at compile time but the
      instance is a local one, then the array will only exist on the stack frame
      when the function with the array is executed.
 3.   Local lifetime, shape bound at runtime: If the shape of the array is not
      known until runtime, then a reference can to the array is created on the
      stack frame and a pointer to the size of the array then used to calculate
      the offset from the start of the array reference on the stack frame.
 4.   Arbitrary lifetime, shape bound at runtime: In Java every array variable is
      a reference to an array object. Declaring int a[] does not create any space
      in memory, it just creates the reference. Only when the keyword new is
      called is the memory allocated. Once allocated the size never changes.
 5.   Arbitrary Lifetime, dynamic shape: It is possible that the size of the array
      can change many times after the initialisation, therefore the strategy in 3
      will not suffice because the space may grow below the initial pointer to the
      array. What must happen is that new memory must be allocated, all of the
      data copied over and then the deletion of the old data.
                          Mark Hennessy CS351 Dept Computer
                                 Science NUI Maynooth                            24
3 - Sets

  Some languages such as Pascal provide
   a builtin composite type of Set that allow
   for union, set difference and intersection.
  OO programming allow a Set type to be
   readily defined using arrays or hash-
   tables.



               Mark Hennessy CS351 Dept Computer
                      Science NUI Maynooth         25
4 - Pointers

    We will have lots of fun with these when
     we cover OO via C++. We will leave the
     discussion on them until then!




                 Mark Hennessy CS351 Dept Computer
                        Science NUI Maynooth         26
5 - Lists
    A list is defined recursively as either the empty set or a list consisting of a
     single element known as the head and a another smaller list called the
     tail.
   In CaML, a list consists of homogeneous elements
  Eg – let l = [1;2;3;4];;
   defines l as a list of 4 ints from 1-4.
   To perform operations on lists:

  let l2 = 5::[1;2;3;4];; => [5;1;2;3;4;]
  hd l2;;                   => 5
  hd [];;                   => Runtime Error
  tl l2;;                   => [1;2;3;4]
  tl [];;                   => Runtime Error
  [1;2] @ [3;4];;          => [1;2;3;4]
  list_length l2;;         => 5

     What is the result of hd [5];; ?
     What is the result of tl [5];;?
                             Mark Hennessy CS351 Dept Computer
                                    Science NUI Maynooth                           27
6 – File Types

  We will leave this until we are doing
   some OO and scripting.
  We just need to know that is obviously
   possible to have different types of file
   available to us when working with I/O.




               Mark Hennessy CS351 Dept Computer
                      Science NUI Maynooth         28
Checking the Equality of Types
    Checking the value of builtin types is trivial:
                Use bitwise comparison for example.
    How should two strings be compared?
            1.   Occupy the same bits over their full length?
            2.   Contain the same sequence of characters?
            3.   Check they print the same ``value’’?
    It all depends on the distinction between the l- and r-values.
     Are we using the value or reference model.
    In the reference model, we can make two kinds of checks:
            1.   Are they both referring (pointing) to the same object?
            2.   Are they both referring to the same value within the object
                 they refer to?
    The first option is known as a shallow comparison.
    The second is a deep comparison.


                         Mark Hennessy CS351 Dept Computer
                                Science NUI Maynooth                           29

								
To top