a study on fundamental principles of programming languages

Upload: tadankiramakrishna2011

Post on 03-Jun-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    1/109

    1

    A study on fundamental principles of programming languages

    By

    [email protected]

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    2/109

    -5-

    INDEX

    1. Introduction (Page6

    !. Procedura" Paradigm (Page #

    $. %unctiona" Paradigm(Page !&

    '. ynta) and emantics(Page 51

    5. *y+es and tructures(Page 6&

    6. ,ogic and *echniues (Page &

    #. /onc"usion(Page 111

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    3/109

    6

    1.Introduction a0out +rinci+"es o +rogramming "anguages.

    Programming languages are one of the most important and direct tools for the

    construction of a computing system. In modern computing different languages are

    routinely used for different levels of abstraction. Aspects related to writing an operating

    system or a device driver are generally very different from those of writing high levelapplications. Moreover, in some typical complex applications, different levels (and thus

    languages) coexist and interoperate, from the !core! logic written e.g. in "## or $ava,

    to the level of scripting, or to the level of !gluing! different applications, usually defined

    by an interpreted high level language (e.g. Python). %i&e natural languages,

    Programming languages are a fundamental means of expression. Algorithms

    implemented using different programming languages may exhibit very different

    characteristics, that can be of aesthetic character, as higher level languages can be very

    synthetic and are usually very expressive' or in terms of performance, as relatively lower

    level languages allow a more direct management of memory and in general of the

    performance of the generated code.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    4/109

    !.Procedura" Paradigm

    The introduction of the architecture was a crucial step in the development of

    electronic computers. he basic idea is that instructions can be encoded as data and

    stored in the memory of the computer. he first conse*uence of this idea is that changing

    and modifying the stored program is simple and efficient. In fact, changes can ta&e place

    at electronic speeds, a very different situation from earlier computers that were

    programmed by plugging wires into panels.

    he second, and ultimately more farreaching, conse*uence is that computers can

    process programs themselves, under program control. In particular, a computer can

    translate a program from one notation to another. hus the storedprogram concept led

    to the development of programming +languages. he history of P%s, li&e the history of

    any technology, is complex. here are advances and setbac&s' ideas that enter the

    mainstream and ideas that end up in a bac&water' even ideas that are submerged for a

    while and later surface in an unexpected place. -ith the benefit of hindsight, we can

    identify several strands in the evolution of P%s. hese strands are commonly called

    +paradigms and, in this course, we survey the paradigms separately although their

    development was interleaved. ources for this section include (-exelblat /01/' -illiams

    and "ampbell2elly /010' 3ergin and 4ibson /005).

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    5/109

    1

    Early Days

    he first P%s evolved from machine code. he first programs used numbers to refer to

    machine addresses. 6ne of the first additions to programming notation was the use of

    symbolic names rather than numbers to represent addresses. 3riefly, it enables the

    programmer to refer to any word in a programme by means of a label or tag attached to

    it arbitrarily by the programmer, instead of by its address in the store. hus, for example,

    a number appearing in the calculation might be labeled 7a89. he programmer could then

    write simply 7A a89 to denote the operation of adding this number into the accumulator,

    without having to specify :ust where the number is located in the machine. (Mutch and

    4ill /0;

    /=> /=O#aN8O.

    . "all by name evaluates the actual parameter exactly as often as it is accessed. (his is

    in contrast with call by value, where the parameter is usually evaluated exactly once, on

    entry to the procedure.) Hor example, if we declare the procedure try as in %isting 5,

    it is safe to call try(x =, /.=Qx), because, ifx =, the expression /.=/x will not be

    evaluated.

    Own ariables. A variable in an Algol procedure can be declared own. he effect is that

    the variable has local scope (it can be accessed only by the statements within the

    procedure)

    but global e/tent (its lifetime is the execution of the entire program).

    !isting #& Lsing call by name

    real procedure try (b, x)' boolean b' real x'

    begin

    try B if b then x else =.=

    end

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    14/109

    /

    Algol 5= and most of its successors, li&e H6EEAF, has a value semantics. A variable

    name stands for a memory addresses that is determined when the bloc& containing the

    variable declaration is entered at runtime. -ith hindsight, we can see that Algol made

    important contributions but also missed some very interesting opportunities.

    . An Algol bloc& without statements is, in effect, a record. Ret Algol 5= does not provide

    records.

    . he local data of an AE is destroyed after the statements of the AE have been executed.

    If the data was retained rather than destroyed, Algol would be a language with modules.

    . An Algol bloc& consists of declarations followed by statements. uppose thatdeclarations and statements could be interleaved in a bloc&. In the following bloc&, D

    denotes a se*uence of declarations and S denotes a se*uence of statements.

    begin

    D/

    S/

    D>

    S>

    end

    A natural interpretation would be that S/ and S> are executed concurrently.

    . 6wn variables were in fact rather problematic in Algol, for various reasons including the

    difficulty of reliably initialiing them . 3ut the concept was importantB it is the separation

    of scope and extent that ultimately leads to ob:ects.

    . he call by name mechanism was a first step towards the important idea that functions

    can be treated as values. he actual parameter in an Algol call, assuming the default

    calling mechanism, is actually a parameter less procedure, as mentioned above. Applying

    this idea consistently throughout the language would have led to high order functions

    and paved the way to functional programming.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    15/109

    /1

    he Algol committee &new what they were doing, however. hey &new that incorporating

    the +missed opportunities described above would have led to significant implementation

    problems. In particular, since they believed that the stac& discipline obtained with nested

    bloc&s was crucial for efficiency, anything that :eopardied it was not acceptable. Algol 5=

    was simple and powerful, but not *uite powerful enough.

    *O'O!

    "636% (ammett /01) introduced structured data and implicit type conversion. -hen"636% was introduced, +programming was more or less synonymous with +numerical

    computation. "636% introduced +data processing, where data meant large numbers of

    characters. he data division of a "636% program contained descriptions of the data to

    be processed. Another important innovation of "636% was a new approach to data types.

    he problem of type conversion had not arisen previously because only a small number

    of types were provided by the P%. "636% introduced many new types, in the sense that

    data could have various degrees of precision, and different representations as text. he

    choice made by the designers of "636% was radicalB type conversion should be

    automatic. he assignment statement in "636% has several forms, including

    M6KC D to R.

    If D and R have different types, the "636% compiler will attempt to find a conversion

    from one type to the other. In most P%s of the time, a single statement translated into a

    small number of machine instructions. In "636%, a single statement could generate a

    large amount of machine code.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    16/109

    /0

    0!12

    Guring the early 5=s, the dominant languages were Algol, "636%, H6EEAF. he

    continuing desire for a +universal language that would be applicable to a wide variety of

    problem domains led I3M to propose a new programming language (originally called FP%

    but changed, after ob:ections from the L29s Fational Physical %aboratory, to P%QI) that

    would combine the best features of these three languages. Insiders at the time referred

    to the new language as +"obAlgoltran. he design principles of P%QI (Eadin /01)

    includedB

    . the language should contain the features necessary for all &inds of programming'

    . a programmer could learn a subset of the language, suitable for a particular application,without having to learn the entire language.

    An important lesson of P%QI is that these design goals are doomed to failure. A

    programmer who has learned a +subset of P%QI is li&ely, li&e all programmers, to ma&e a

    mista&e. -ith luc&, the compiler will detect the error and provide a diagnostic message

    that is incomprehensible to the programmer because it refers to a part of the language

    outside the learned subset. More probably, the compiler will not detect the error and the

    program will behave in a way that is inexplicable to the programmer, again because it is

    outside the learned subset.

    P%QI extends the automatic type conversion facilities of "636% to an extreme degree. Hor

    example,

    the expression (4elernter and $agannathan /00=)

    (9;9 SS 1) # /

    is evaluated as followsB

    /. "onvert the integer 1 to the string 919.

    >. "oncatenate the strings 9;9 and 919, obtaining 9;19.

    8. "onvert the string 9;19 to the integer ;1.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    17/109

    >=

    he compiler9s policy, on encountering an assignmentx E, might be paraphrased asB

    +Go everything possible to compile this statement' as far as possible, avoid issuing any

    diagnostic message that would tell the programmer what is happening. P%QI did

    introduce some important new features into P%s. hey were not all welldesigned, but

    their existence encouraged others to produce better designs.

    . Cvery variable has a storage classB static, automatic, based, or controlled. ome of

    these were later incorporated into ".

    . An ob:ect associated with a based variablex re*uires explicit allocation and is placed onthe heap rather than the stac&. ince we can execute the statement allocatex as often

    as necessary, based variables provide a form of template.

    . P%QI provides a wide range of programmerdefined types. ypes, however, could not be

    named.

    . P%QI provided a simple, and not very safe, form of exception handling. tatements of

    the following form are allowed anywhere in the programB

    6F condition

    3C4IF'

    . . . .

    CFG'

    If the condition (which might be 6KCEH%6-, PEIFCE 6L 6H PAPCE, etc.) becomes

    ELC, control is transferred to whichever 6F statement for that condition was most

    recently executed. After the statements between 3C4IF and CFG (the handler) have

    been executed, control returns to the statement that raised the exception or, if the

    handler contains a 466 statement, to the target of that statement.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    18/109

    3+

    Algol #4

    -hereas Algol 5= is a simple and expressive language, its successor Algol 51 (van

    -i:ngaarden et al. /0;' %indsey /005) is much more complex. he main design

    principle of Algol 51 was orthogonalityB the language was to be defined using a number

    of basic concepts that could be combined in arbitrary ways. Although it is true that lack

    of orthogonality can be a nuisance in P%s, it does not necessarily follow that orthogonality

    is always a good thing.

    he important features introduced by Algol 51 include the following.

    . he language was described in a formal notation that specified the complete syntax and

    semantics of the language (van -i:ngaarden et al. /0;). he fact that the Eeport was

    very hard to understand may have contributed to the slow acceptance of the language.

    . 6perator overloadingB programmers can provide new definitions for standard operators

    such as +#. Cven the priority of these operators can be altered.

    . Algol 51 has a very uniform notation for declarations and other entities. Hor example,

    Algol 51 uses the same syntax (mode name expression) for types, constants,

    variables, and functions. his implies that, for all these entities, there must be forms of

    expression that yield appropriate values.

    . In a collateral clause of the form (x, y, z), the expressionsx, y, andz can be

    evaluated in any order, or concurrently. In a function call f(x, y, z), the argument list is a

    collateral clause. "ollateral clauses provide a good, and early, example of the idea that a

    P% specification should intentionally leave some implementation details undefined. In this

    example, the Algol 51 report does not specify the order of evaluation of the expressions

    in a collateral clause. his gives the implementor freedom to use any order of evaluation

    and hence, perhaps, to optimie.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    19/109

    >>

    . he operator ref stands for +reference and means, roughly, +use the address rather

    than the value. his single &eyword introduces call by reference, pointers, dynamic data

    structures, and other features to the language. It appears in " in the form of the

    operators +T and +U.

    . A large vocabulary of P% terms, some of which have become part of the culture (cast,

    coercion, narrowing, . . . .) and some of which have not (mode, wea& context, voiding,. .

    . .).

    %i&e Algol 5=, Algol 51 was not widely used, although it was popular for a while in variousparts of Curope. he ideas that Algol 51 introduced, however, have been widely imitated.

    0ascal

    Pascal was designed by -irth (/005) as a reaction to the complexity of Algol 51, P%QI,

    and other languages that were becoming popular in the late 5=s. -irth made extensive

    use of the ideas of Gi:&stra and ?oare (later published as (Gahl, Gi:&stra, and ?oare

    /0>)), especially ?oare9s ideas of data structuring. he important contributions of Pascal

    included the following.

    . Pascal demonstrated that a P% could be simple yet powerful.

    . he type system of Pascal was based on primitives (integer, real, bool, . . . .) and

    mechanisms for building structured types (array, record, file, set, . . . .). hus data types

    in Pascal form a recursive hierarchy :ust as bloc&s do in Algol 5=.

    . Pascal provides no implicit type conversions other than subrange to integer and integer

    to real. All other type conversions are explicit (even when no action is re*uired) and the

    compiler chec&s type correctness.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    20/109

    >8

    . Pascal was designed to match -irth9s (/0/) ideas of program development by

    stepwise refinement.Pascal is a &ind of +fill in the blan&s language in which all programs

    have a similar structure, determined by the relatively strict syntax. Programmers are

    expected to start with a complete but s&eletal +program and flesh it out in a series of

    refinement steps, each of which ma&es certain decisions and adds new details. he

    monolithic structure that this idea imposes on programs is a drawbac& of Pascal because

    it prevents independent compilation of components.

    Pascal was a failure because it was too simple. 3ecause of the perceived missingfeatures, supersets were developed and, inevitably, these became incompatible. he first

    version of +tandard Pascal was almost useless as a practical programming language

    and the Eevised tandard described a usable language but appeared only after most

    people had lost interest in Pascal. %i&e Algol 5=, Pascal missed important opportunities.

    he record type was a useful innovation (although very similar to the Algol 51 struct) but

    allowed data only. Allowing functions in a record declaration would have paved the way to

    modular and even ob:ect oriented programming. Fevertheless, Pascal had a strong

    influence on many later languages. Its most important innovations were probably the

    combination of simplicity, data type declarations, and static type chec&ing.

    5odula63

    -irth (/01>) followed Pascal with ModulaV>, which inherits Pascal9s strengths and, to

    some extent, removes Pascal9s wea&nesses. he important contribution of ModulaV> was,

    of course, the introduction of modules. (-irth9s first design, Modula, was never

    completed. ModulaV> was the product of a sabbatical year in "alifornia, where -irth

    wor&ed with the designers of Mesa, another early modular language.)

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    21/109

    > has an interface and an implementation. he interface provides

    information about the use of the module to both the programmer and the compiler. he

    implementation contains the +secret information about the module. his design has the

    unfortunate conse*uence that some information that should be secret must be put into

    the interface. Hor example, the compiler must &now the sie of the ob:ect in order to

    declare an instance of it. his implies that the sie must be deducible from the interface

    which implies, in turn, that the interface must contain the representation of the ob:ect.

    (he same problem appears again in "##.)

    ModulaV> provides a limited escape from this dilemmaB a programmer can define an

    +opa*ue type with a hidden representation. In this case, the interface contains only a

    pointer to the instance and the representation can be placed in the implementation

    module. he important features of ModulaV> areB

    . Modules with separated interface and implementation descriptions (based on

    Mesa). .

    "oroutines.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    22/109

    >;

    *

    " is a very pragmatic P%. Eitchie (Eitchie /005) designed it for a particular tas& @

    systemsprogramming@ for which it has been widely used. he enormous success of " is

    partly accidental. LFID, after 3ell released it to universities, became popular, with good

    reason. ince LFID depended heavily on ", the spread of LFID inevitably led to the

    spread of ". " is based on a small number of primitive concepts. Hor example, arrays are

    defined in terms of pointers and pointer arithmetic. his is both the strength andwea&ness of ". he number of concepts is small, but " does not provide real support for

    arrays, strings, or boolean operations." is a lowlevel language by comparison with the

    other P%s discussed in this section. It is designed to be easy to compile and to produce

    efficient ob:ect code. he compiler is assumed to be rather unsophisticated (a reasonable

    assumption for a compiler running on a PGPQ// in the late sixties) and in need of hints

    such as register. " is notable for its concise syntax. ome syntactic features are inherited

    from Algol 51 (for example, # and other assignment operators) and others are uni*ue

    to " and "## (for example, postfix and prefix ## and ).

    Ada

    Ada (-hita&er /005) represents the last ma:or effort in procedural language design. It is

    a large and complex language that combines then&nown programming features with

    little attempt at consolidation. It was the first widelyused language to provide full

    support for concurrency, with interactions chec&ed by the compiler, but this aspect of the

    language proved hard to implement.

    Ada provides templates for procedures, record types, generic pac&ages, and tas& types.

    he corresponding ob:ects areB bloc&s and records (representable in the language)' and

    pac&ages and tas&s (not representable in the language). It is not clear why four distinct

    mechanisms are re*uired (4elernter and $agannathan /00=).

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    23/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    24/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    25/109

    >1

    $. %unctiona" Paradigm

    Procedural programming is based on instructions (+do something) but, inevitably,

    procedural Pls also provide expressions (+calculate something). he &ey insight of

    functional programming (HP) is that everything can be done with expressionsB the

    commands are unnecessary.

    his point of view has a solid foundation in theory. uring (/085) introduced an abstract

    model of +programming, now &nown as the uring machine. 2leene (/085) and "hurch

    (/0.

    he same conventions apply in logic with +function replaced by +function or predicate.

    In firstorder logic, *uantifiers can bind variables only' in a high order logic, *uantifiers

    can bind predicates.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    26/109

    >0

    !2)0

    Anyone could learn LISP in one day, except that if they already knew F!"!A#, it

    would take three day$. Marvin Mins&y

    Hunctional programming was introduced in /0;1 in the form of %IP by $ohn Mc"arthy.

    he following account of the development of %IP is based on Mc"arthy9s (/01) history.

    he important early decisions in the design of %IP wereB

    . to provide list processing (which already existed in languages such as Information

    Processing %anguage (IP%) and H6EEAF %ist Processing %anguage (H%P%))'

    . to use a prefix notation (emphasiing the operator rather than the operands of an

    expression)'

    . to use the concept of +function as widely as possible (cons for list construction' car and

    cdr for extracting list components' cond for conditional, etc.)'

    . to provide higher order functions and hence a notation for functions (based on "hurch9s

    (/0

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    27/109

    8=

    Another way to show that %IP was neater than uring machines was to write a universal

    %IP function and show that it is briefer and more comprehensible than the description of

    a universal uring machine. his was the %IP function e%al Ne, aO, which computes the

    value of a %IP expression e, the second argument a being a list of assignments of values

    to variables. . . . -riting e%al re*uired inventing a notation for representing %IP

    functions as %IP data, and such a notation was devised for the purpose of the paper

    with no thought that it would be used to express %IP programs in practice. (Mc"arthy

    /01)

    After the paper was written, Mc"arthy9s graduate student . E. Eussel noticed that e%al

    could be used as an interpreter for %IP and handcoded it, thereby producing the first

    %IP interpreter. oon afterwards, imothy ?art and Michael %evin wrote a %IP compiler

    in %IP' this is probably the first instance of a compiler written in the language that it

    compiled.

    he function application f(x, y) is written in %IP as (f x y). he function name always

    comes firstB a # & is written in %IP as (# a b). All expressions are enclosed in

    parentheses and can be nested to arbitrary depth.

    here is a simple relationship between the text of an expression and its representation in

    memory. An atom is a simple ob:ect such as a name or a number. A list is a data

    structure composed of conscells (so called because they are constructed by the function

    cons)' each conscell has two pointers and each pointer points either to another conscell

    or to an atom. Higure / shows the list structure corresponding to the expression (A (3

    ")). Cach box represents a conscell. here are two lists, each with two elements, and

    each terminated with FI%. he diagram is simplified in that the atoms A, 3, ", and FI%

    would themselves be list structures in an actual %IP system.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    28/109

    8/

    he function cons constructs a list from its head and tailB (cons head tail). he value of

    (car list) is the head of the list and the value of (cdr list) is the tail of the list. husB

    (car (cons head tail)) J head

    (cdr (cons head tail)) J tail

    he names car and cdr originated in I3M =< hardware' they are abbreviations for

    +contents of address register (the top /1 bits of a 85bit word) and +contents of

    decrement register (the bottom /1 bits). It is easy to translate between list expressionsand the corresponding data structures. here is a function eval (mentioned in the

    *uotation above) that evaluates a stored list expression. "onse*uently, it is

    straightforward to build languages and systems +on top of %IP and %IP is often used in

    this way.

    It is interesting to note that the close relationship between code and data in %IP mimics

    the von Feumann architecture at a higher level of abstraction. %IP was the first in a long

    line of functional programming (HP) languages. Its principal contributions are listed

    below.

    Names. In procedural P%s, a name denotes a storage location (value semantics). In %IP,

    a name is a reference to an ob:ect, not a location (reference semantics). In the Algol

    se*uence

    int n'

    n B >'

    n B 8'

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    29/109

    8>

    the declaration int n' assigns a name to a location, or +box, that can contain an integer.

    he next two statements put different values, first > then 8, into that box. In the %IP

    se*uence

    (progn

    (set* x (car structure))

    (set* x (cdr structure)))

    x becomes a reference first to (car structure) and then to (cdr structure). he twoob:ects have different memory addresses. A conse*uence of the use of names as

    references to ob:ects is that eventually there will be ob:ects for which there are no

    referencesB these ob:ects are +garbage and must be automatically reclaimed if the

    interpreter is not to run out of memory. he alternative @ re*uiring the programmer to

    explicitly deallocate old cells @ would add considerable complexity to the tas& of writing

    %IP programs. Fevertheless, the decision to include automatic garbage collection (in

    /0;1J) was courageous and influential. A P% in which variable names are references to

    ob:ects in memory is said to have reference semantics. All HP%s and most 66P%s have

    reference semantics. Fote that reference semantics is not the same as +pointers in

    languages such as Pascal and ". A pointer variable stands for a location in memory and

    therefore has value semantics' it :ust so happens that the location is used to store the

    address of another ob:ect.

    !ambda. %IP uses +lambda expressions, based on "hurch9s calculus, to denote

    functions. Hor example, the function that s*uares its argument is written

    (lambda (x) (T x x))

    by analogy to "hurch9s f x .x>. -e can apply a lambda expression to an argument to

    obtain the value of a function application. Hor example, the expression

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    30/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    31/109

    8,8,

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    47/109

    ;=

    fun reduce f u NO u

    S reduce f u (xBBxs) f x (reduce f u xs)'

    val reduce fn B (9a 9b 9b) 9b 9a list 9b

    -e can also define a sorting function as

    val sort reduce insert nil'

    val sort fn B int list int list

    where insert is the function that inserts a number into an ordered list, preserving the

    orderingB fun insert xBint NO xBBNO

    S insert x (yBBys) if x _ y then xBByBBys else yBBinsert x ys'

    val insert fn B int int list int list

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    48/109

    ;/

    '.ynta) and emantics

    !yntax! is often used as a synonym to !grammar.! It deals with what a language loo&s

    li&e and how that language is structured. It examines the pieces of a sentence, such as

    nouns, ad:ectives and verbs, and how to order them to create a coherent language.

    )ynta/ refers to the ways symbols may be combined to create wellformed sentences

    (or programs) in the language. yntax defines the formal relations between the

    constituents of a language, thereby providing a structural description of the various

    expressions that ma&e up legal strings in the language. yntax deals solely with the form

    and structure of symbols in a language without any consideration given to their meaning.

    !emantics! loo&s at the meaning of a language. hat can include the basic,

    straightforward definitions of words or fine distinctions between similar words. -hen

    people refer to groups disagreeing over !semantics,! it typically means that they cannot

    agree on how to refer to a term or concept. Hor example, different groups of people may

    disagree over whether to call a political position !prochoice! or !proabortion! based on

    the subtle semantic differences between the two terms.

    emantics reveals the meaning of syntactically valid strings in a language. Hor natural

    languages, this means correlating sentences and phrases with the ob:ects, thoughts, and

    feelings of our experiences. Hor programming languages, semantics describes the

    behavior that a computer follows when executing a program in the language. -e might

    disclose this behavior by describing the relationship between the input and output of a

    program or by a stepbystep explanation of how a program will execute on a real or an

    abstract machine. he syntax of a programming language is commonly divided into two

    parts, the le/ical synta/ that describes the smallest units with significance, called

    to(ens , and the phrase8structur e synta/ that explains how to&ens are arranged

    into programs. he lexical syntax recognies identifiers, numerals, special symbols, and

    reserved words as if a syntactic category _to&en had the definitionB

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    49/109

    ;>

    _to&en BB _identifier S _numeral S _reserved word S _relation

    S _wea& op S _strong op S &9 S : S ; S S < S &

    where

    _program BB program _identifier is _bloc&

    _bloc& BB _declaration se* begin _command se* end

    _declaration se* BB e S _declaration _declaration se*

    _declaration BB var _variable list & _type S >9 S =>

    _wea& op BB ? S 6

    _strong op BB @ S 1

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    50/109

    ;8

    _identifier BB _letter S _identifier _letter S _identifier _digit

    _letter BB a S b S c S d S e S f S g S h S i S S ( S l S m

    S n S o S p S B S r S s S t S u S v S w S / S y S 7

    _numeral BB _digit S _digit _numeral

    _digit BB $ S + S 3 S % S - S , S # S C S 4 S

    3FH for -ren

    _reserved word BB program S is S begin S end S var S integer

    S boolean S read S write S s(ip S while S do S if

    S then S else S and S or S true S false S not.

    _program BB program _identifier is _bloc&

    _bloc& BB _declaration se* begin _command se* end

    _declaration se* BB e S _declaration _declaration se*

    _declaration BB var _variable list & _type 9 S =>

    _wea& op BB ? S 6

    _strong op BB @ S 1

    _identifier BB _letter S _identifier _letter S _identifier _digit

    _letter BB a S b S c S d S e S f S g S h S i S S ( S l S m

    S n S o S p S B S r S s S t S u S v S w S / S y S 7

    _numeral BB _digit S _digit _numeral_digit BB $ S + S 3 S % S - S , S # S C S 4 S

    uch a division of syntax into lexical issues and the structure of programs in terms of

    to&ens corresponds to the way programming languages are normally implemented.

    Programs as text are presented to a le/ical analy7er or scanner that reads characters

    and produces a list of to&ens ta&en from the le/icon , a collection of possible to&ens of

    the language. ince semantics ascribes meaning to programs in terms of the structure of

    their phrases, the details of lexical syntax are irrelevant. he internal structure of to&ens

    is immaterial, and only intelligible to&ens ta&e part in providing semantics to a program.

    In the above , the productions defining _relation, _wea& op,

    _strong op, _identifier, _letter, _numeral, and _digit form the lexical syntax of

    -ren, although the first three rules may be used as abbreviations in the phrasestructure

    syntax of the language.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    52/109

    ;;

    A')TRA*T )NTA

    he 3FH definition of a programming language is sometimes referred to as the concrete

    synta/ of the language since it tells how to recognie the physical text of a program.

    oftware utilities ta&e a program as a file of characters, recognie that it satisfies the

    contextfree syntax for the language, and produce a derivation tree exhibiting its

    structure. his software usually decomposes into two partsB a scanner or le/ical

    analy7er that reads the text and creates a list of to&ens and a parser or syntactic

    analy7er that forms a derivation tree from the to&en list based on the 3FH definition.

    A TGO8!EE! HRA55AR FOR GREN

    he twolevel grammar that we construct for -ren performs all necessary context

    chec&ing. he primary focus is on ensuring that identifiers are not multiply declared, that

    variables used in the program have been declared, and that their usage is consistent with

    their types . All declaration information is present in a metanotion called GC"%C, which

    is associated with the contextsensitive portions of commands. -e use the following

    -ren program for illustration as we develop the twolevel grammarB program p is

    var x y & integer),(Proof/, Proof>)) B prove(4oal/,Proof/),

    prove(4oal>,Proof>).

    prove(4oal, 4oal_Proof) B clause(4oal, 3ody), prove(3ody, Proof).

    prove(4oal,fail) B fail.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    60/109

    58

    ?ere are the results of our test casesB

    +4+

    B prove::memb:Mabc;memb:Mbcd;;0roof;.

    D b

    Proof memb(b,Na,b,cO)_memb(b,Nb,cO)_true,

    memb(b,Nb,c,dO)_true

    B prove::memb:Mabc;memb:Mdef;; 0roof;.

    no

    B prove:::memb:Mabc;memb:Mbcd;;

    memb:Mcde;; 0roof;.

    D c

    Proof

    (memb(c,Na,b,cO)_memb(c,Nb,cO)_memb(c,NcO)_true,

    memb(c,Nb,c,dO)_memb(c,Nc,dO)_true),

    memb(c,Nc,d,eO)_true

    TRAN)!AT2ONA! )E5ANT2*)

    -ren program being translated obeys the contextsensitive conditions for the language

    as well as the contextfree grammar. -e parse the declaration section to ensure that the

    3FH is correct, but no attributes are associated with the declaration section. "ontext

    chec&ing can be combined with code generation in a single attribute grammar, but we

    leave this tas& unfinished at this time.

    he machine code is based on a primitive architecture with a single accumulator

    (Acc) and a memory addressable with symbolic labels and capable of holding integer

    values. In this translation, 3oolean values are simulated by integers. -e use names to

    indicate symbolic locations. he hypothetical machine has a loadQstore architectureB

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    61/109

    5 8TYi. Fote that simplification of products of complex

    expressions can be effected by expanding the product. implification of *uotients, roots,

    and other functions of complex expressions can usually be accomplished by using

    the realpart, imagpart, rectform, polarform, abs, carg functions.

    Hunctions and Kariables for Fumbers

    HunctionB bfloatexpr0

    "onverts all numbers and functions of numbers in expr to bigfloat numbers. he

    number of significant digits in the resulting bigfloats is specified by the global

    variable fpprec.

    -hen float>bfis false a warning message is printed when a floating point number is

    converted into a bigfloat number (since this may lead to loss of precision).

    6ption variableB bftorat

    Gefault valueB false

    bftorat controls the conversion of bfloats to rational numbers.

    -hen bftorat is false, ratepsilonwill be used to control the conversion (this results in

    relatively small rational numbers). -hen bftorat is true, the rational number generated

    will accurately represent the bfloat.

    http://maxima.sourceforge.net/docs/manual/en/maxima_5.html#fpprechttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#float2bfhttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#ratepsilonhttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#float2bfhttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#ratepsilonhttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#fpprec
  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    66/109

    50

    FoteB bftorat has no effect on the transformation to rational numbers with the

    function rationalie.

    CxampleB

    (Yi/) ratepsilonB/e by /Q/= /.=3/

    /

    (Yo>)QEQ

    /=

    (Yi8) rat(bfloat(/////Q//////)), bftoratBtrue'

    rat replaced 0.0000=00000/3> by /////Q////// 0.0000=00000/3>

    /////

    (Yo8)QEQ

    //////

    http://maxima.sourceforge.net/docs/manual/en/maxima_5.html#rationalizehttp://maxima.sourceforge.net/docs/manual/en/maxima_5.html#rationalize
  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    67/109

    C$

    3.)trings

    trings (*uoted character se*uences) are enclosed in double *uote mar&s ! for input, and

    displayed with or without the *uote mar&s, depending on the global variable stringdisp.

    trings may contain any characters, including embedded tab, newline, and carriage

    return characters.

    he se*uence \! is recognied as a literal double *uote, and \\ as a literal bac&slash.

    -hen bac&slash appears at the end of a line, the bac&slash and the line termination

    (either newline or carriage return and newline) are ignored, so that the string continues

    with the next line. Fo other special combinations of bac&slash with another character are

    recognied' when bac&slash appears before any character other than !, \, or a line

    termination, the bac&slash is ignored. here is no way to represent a special character

    (such as tab, newline, or carriage return) except by embedding the literal character in

    the string. here is no character type in Maxima' a single character is represented as a

    onecharacter string. he stringproc addon pac&age contains many functions for wor&ing

    with strings.

    CxamplesB

    Yi/) s/ B !his is a string.!'

    (Yo/) his is a string.

    (Yi>) s> B !Cmbedded \!double *uotes\! and bac&slash \\ characters.!'

    (Yo>) Cmbedded !double *uotes! and bac&slash \ characters.

    (Yi8) s8 B !Cmbedded line termination

    in this string.!'

    (Yo8) Cmbedded line termination

    in this string.

    (Yi

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    68/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    69/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    70/109

    8

    "onstantB Pi

    Yi represents the imaginary unit, $4rt5 '0.

    "onstantB falsefalse represents the 3oolean constant of the same name. Maxima implements false by

    the value FI% in %isp.

    "onstantB Pgamma

    he CulerMascheroni constant, =.;>/;550 ....

    "onstantB ind

    ind represents a bounded, indefinite result.

    ee also limit.

    (Yi/) limit (sin(/Qx), x, =)'

    (Yo/) ind

    "onstantB Pphi

    Yphi represents the socalled )olden *ean, ' 6 $4rt(00/2. he numeric value

    of Yphi is the doubleprecision floatingpoint value /.5/1=88011 Yphi /) andalgebraicB true, ratsimpcan simplify some

    expressions containing Yphi.

    http://maxima.sourceforge.net/docs/manual/en/maxima_17.html#limithttp://maxima.sourceforge.net/docs/manual/en/maxima_29.html#fibtophihttp://maxima.sourceforge.net/docs/manual/en/maxima_14.html#ratsimphttp://maxima.sourceforge.net/docs/manual/en/maxima_17.html#limithttp://maxima.sourceforge.net/docs/manual/en/maxima_29.html#fibtophihttp://maxima.sourceforge.net/docs/manual/en/maxima_14.html#ratsimp
  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    71/109

    ) fib(n # /) # fib(n) # fib(n /)

    (Yi8) fibtophi (Y)'

    n # / n # / n n

    Yphi (/ Yphi) Yphi (/ Yphi)

    (Yo8) #

    > Yphi / > Yphi /

    n / n /

    Yphi (/ Yphi)

    #

    > Yphi /

    (Yi

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    72/109

    C,

    - !ists

    %ists are the basic building bloc& for Maxima and %isp. All data types other than arrays,

    hash tables, numbers are represented as %isp lists, hese %isp lists have the form

    %ists are the basic building bloc& for Maxima and %isp. All data types other than arrays,

    hash tables, numbers are represented as %isp lists, hese %isp lists have the form

    ((MP%L) A >)

    to indicate an expression a#>. At Maxima level one would see the infix notation a#>.Maxima also has lists which are printed as

    N/, >, , x#yO

    for a list with < elements. Internally this corresponds to a %isp list of the form

    ((M%I) / > ((MP%L) D R ))

    he flag which denotes the type field of the Maxima expression is a list itself, since after

    it has been through the simplifier the list would become

    ((M%I IMP) / > ((MP%L IMP) D R))

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    73/109

    5

    ariables for !ists

    6peratorB M

    6peratorB

    N and O mar& the beginning and end, respectively, of a list.

    N and O also enclose the subscripts of a list, array, hash array, or array function.

    CxamplesB

    (Yi/) xB Na, b, cO'

    (Yo/) Na, b, cO

    (Yi>) xN8O'

    (Yo>) c

    (Yi8) array (y, fixnum, 8)'

    (Yo8) y

    (YiOB Ypi'

    (YoO'

    (Yo;) Ypi

    (Yi5) NfooOB bar'

    (Yo5) bar

    (Yi) NfooO'

    (Yo) bar

    (Yi1) gN&O B /Q(&>#/)'

    /

    (Yo1) g B & >

    & # /

    (Yi0) gN/=O'

    /

    (Yo0)

    /=/

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    74/109

    HunctionB appendli$t1', 3, li$t1n0

    Eeturns a single list of the elements of li$t1'followed by the elements of li$t12,

    append also wor&s on general expressions, e.g. append (f(a,b),

    f(c,d,e))' yields f(a,b,c,d,e).

    Go example(append)' for an example.

    HunctionB assockey, li$t, default0

    HunctionB assockey, li$t0

    his function searches for the keyin the left hand side of the input li$tof the

    form Nx,y,,...O where each of the li$telements is an expression of a binary operand and >

    elements. Hor example x/, >8, Na,bO etc. he keyis chec&ed against the first

    operand. assoc returns the second operand if the &ey is found. If the &ey is not found it

    either returns the defaultvalue. defaultis optional and defaults to false.

    HunctionB consexpr, li$t0

    Eeturns a new list constructed of the element expras its first element, followed by the

    elements of li$t. cons also wor&s on other expressions, e.g. cons(x, f(a,b,c))'

    f(x,a,b,c).

    HunctionB deleteexpr1', expr120

    HunctionB deleteexpr1', expr12, n0

    delete(expr1', expr12) removes from expr12any arguments of its toplevel operator

    which are the same (as determined by !!) as expr1'. Fote that !! tests for formal

    e*uality, not e*uivalence. Fote also that arguments of subexpressions are not affected.

    expr1'may be an atom or a nonatomic expression. expr12may be any nonatomic

    expression. delete returns a new expression' it does not modify expr12.

    delete(expr1', expr12, n) removes from expr12the first narguments of the toplevel

    operator which are the same asexpr1'. If there are fewer than nsuch arguments, then

    all such arguments are removed.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    75/109

    1

    CxamplesB

    Eemoving elements from a list.

    (Yi/) delete (y, Nw, x, y, , , y, x, wO)'

    (Yo/) Nw, x, , , x, wO

    Eemoving terms from a sum.

    (Yi/) delete (sin(x), x # sin(x) # y)'

    (Yo/) y # x

    Eemoving factors from a product.

    (Yi/) delete (u x, (u w)T(u x)T(u y)T(u ))'

    (Yo/) (u w) (u y) (u )

    Eemoving arguments from an arbitrary expression.

    (Yi/) delete (a, foo (a, b, c, d, a))'

    (Yo/) foo(b, c, d)

    %imit the number of removed arguments.

    (Yi/) delete (a, foo (a, b, a, c, d, a), >)'

    (Yo/) foo(b, c, d, a)

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    76/109

    0

    -hether arguments are the same as expr1'is determined by !!. Arguments which

    are e*ual but not !! are not removed.

    (Yi/) Nis (e*ual (=, =)), is (e*ual (=, =.=)), is (e*ual (=, =b=))O'

    ratB replaced =.= by =Q/ =.=

    rat replaced =.=3= by =Q/ =.=3=

    (Yo/) Ntrue, true, trueO

    (Yi>) Nis (= =), is (= =.=), is (= =b=)O'

    (Yo>) Ntrue, false, falseO

    (Yi8) delete (=, N=, =.=, =b=O)'

    (Yo8) N=.=, =.=b=O(Yi y>))'

    (Yo y>)'

    (Yo;) false

    (Yi5) delete ((x # y)T(x y), N(x # y)T(x y), x> y>O)'

    > >

    (Yo5) Nx y O

    , Arrays

    Hunctions and Kariables for Arrays

    HunctionB arrayna*e, di*1', 3, di*1n0HunctionB arrayna*e, type, di*1', 3, di*1n0

    HunctionB array7na*e1', 3, na*e1*8, di*1', 3, di*1n0

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    77/109

    1=

    "reates an ndimensional array. n may be less than or e*ual to ;. he subscripts for

    the ith dimension are the integers running from = to dimi.

    array (name, dim/, ..., dimn) creates a general array.

    array (name, type, dim/, ..., dimn) creates an array, with elements of a specified

    type. type can be fixnum for integers of limited sie or flonum for floatingpoint

    numbers.

    array (Nname/, ..., namemO, dim/, ..., dimn) creates m arrays, all of the same

    dimensions.

    If the user assigns to a subscripted variable before declaring the corresponding

    array, an undeclared array is created. Lndeclared arrays, otherwise &nown as

    hashed arrays (because hash coding is done on the subscripts), are more general

    than declared arrays. he user does not declare their maximum sie, and they grow

    dynamically by hashing as more elements are assigned values. he subscripts of

    undeclared arrays need not even be numbers. ?owever, unless an array is rather

    sparse, it is probably more efficient to declare it when possible than to leave it

    undeclared. he array function can be used to transform an undeclared array into a

    declared array.

    HunctionB arrayapplyA, 7i1', 3, i1n80

    CvaluatesANi1', ..., i1nO, whereAis an array and i1', , i1nare integers.

    his is reminiscent of apply, except the first argument is an array instead of a function.

    HunctionB arrayinfoA0

    Eeturns information about the arrayA. he argumentAmay be a declared array, an

    undeclared (hashed) array, an array function, or a subscripted function.

    Hor declared arrays, arrayinfo returns a list comprising the atom declared, the number of

    dimensions, and the sie of each dimension. he elements of the array, both bound and

    unbound, are returned by listarray.

    http://maxima.sourceforge.net/docs/manual/en/maxima_36.html#applyhttp://maxima.sourceforge.net/docs/manual/en/maxima_36.html#apply
  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    78/109

    1/

    Hor undeclared arrays (hashed arrays), arrayinfo returns a list comprising the

    atom hashed, the number of subscripts, and the subscripts of every element which has a

    value. he values are returned by listarray.

    Hor array functions, arrayinfo returns a list comprising the atom hashed, the number of

    subscripts, and any subscript values for which there are stored function values. he

    stored function values are returned by listarray.

    Hor subscripted functions, arrayinfo returns a list comprising the atom hashed, the

    number of subscripts, and any subscript values for which there are lambda expressions.

    he lambda expressions are returned by listarray.

    CxamplesB

    arrayinfo and listarray applied to a declared array.

    (Yi/) array (aa, >, 8)'

    (Yo/) aa

    (Yi>) aa N>, 8O B Ypi'

    (Yo>) Ypi(Yi8) aa N/, >O B Ye'

    (Yo8) Ye

    (Yi

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    79/109

    1>

    arrayinfo and listarray applied to an undeclared (hashed) array.

    (Yi/) bb NH66O B (a # b)>'

    >

    (Yo/) (b # a)

    (Yi>) bb N3AEO B (c d)8'

    8

    (Yo>) (c d)

    (Yi8) arrayinfo (bb)'

    (Yo8) Nhashed, /, N3AEO, NH66OO

    (Yi) cc Nu, vO'

    v

    (Yo>)

    u

    (Yi8) cc N

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    80/109

    18

    arrayinfo and listarray applied to a subscripted function.

    (Yi/) dd NxO (y) B y x'

    x

    (Yo/) dd (y) B y

    x

    (Yi>) dd Na # bO'

    b # a

    (Yo>) lambda(NyO, y )

    (Yi8) dd Nv uO'

    v u(Yo8) lambda(NyO, y )

    (Yi

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    81/109

    1

    (Yo>) (b # a)

    (Yi8) cc NxO B xQ/=='

    x

    (Yo8) cc B

    x /==

    (Yid e*ual to false), structure instances are displayed without the

    field names.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    82/109

    1;

    here is no way to use a field name as a function name, although a field value can be a

    lambda expression. For can the values of fields be restricted to certain types' any field

    can be assigned any &ind of expression. here is no way to ma&e some fields accessible

    or inaccessible in different contexts' all fields are always visible.

    4lobal variableB structures

    structures is the list of userdefined structures defined by defstruct.

    HunctionB defstructSa1', 3, a1n00

    HunctionB defstructSa1' 9 %1', 3, a1n 9 %1n00

    Gefine a structure, which is a list of named fields a1', , a1nassociated with a

    symbol S. An instance of a structure is :ust an expression which has operator Sand

    exactly n arguments. new(S) creates a new instance of structure S.

    An argument which is :ust a symbol aspecifies the name of a field. An argument which is

    an e*uation a %specifies the field name aand its default value %. he default value can

    be any expression.

    defstruct puts Son the list of userdefined structures, structures.

    &ill(S) removes Sfrom the list of userdefined structures, and removes the structure

    definition.

    CxamplesB

    (Yi/) defstruct (foo (a, b, c))'

    (Yo/) Nfoo(a, b, c)O

    (Yi>) structures'

    (Yo>) Nfoo(a, b, c)O

    (Yi8) new (foo)'

    (Yo8) foo(a, b, c)

    (Yi8, y Ypi))'

    (Yo8, y Ypi)O

    (Yi;) structures'

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    83/109

    (Yo;) Nfoo(a, b, c), bar(v, w, x />8, y Ypi)O

    (Yi5) new (bar)'

    (Yo5) bar(v, w, x />8, y Ypi)

    (Yi) &ill (foo)'

    (Yo) done

    (Yi1) structures'

    (Yo1) Nbar(v, w, x />8, y Ypi)O

    HunctionB newS0

    HunctionB newS %1', 3, %1n00

    new creates new instances of structures.

    new(S) creates a new instance of structure Sin which each field is assigned its defaultvalue, if any, or no value at all if no default was specified in the structure definition.

    new(S(%1', ..., %1n)) creates a new instance of Sin which fields are assigned the

    values %1', , %1n.

    CxamplesB

    (Yi/) defstruct (foo (w, x Ye, y , ))'

    (Yo/) Nfoo(w, x Ye, y , )O

    (Yi>) new (foo)'

    (Yo>) foo(w, x Ye, y , )

    (Yi8) new (foo (/, >,

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    84/109

    1

    6peratorB Q

    is the structure field access operator. he expressionx arefers to the value of

    field aof the structure instancex. he field name is not evaluated.

    If the field ainxhas not been assigned a value,x aevaluates to itself.

    &ill(x a) removes the value of field ainx.

    CxamplesB

    (Yi/) defstruct (foo (x, y, ))'

    (Yo/) Nfoo(x, y, )O

    (Yi>) u B new (foo (/>8, a b, Ypi))'

    (Yo>) foo(x />8, y a b, Ypi)

    (Yi8) u'

    (Yo8) Ypi

    (Yi8, y a b, Ye)

    (Yi5) &ill (u)'

    (Yo5) done

    (Yi) u'

    (Yo) foo(x />8, y a b, )

    (Yi1) u'

    (Yo1) u

    he field name is not evaluated.

    (Yi/) defstruct (bar (g, h))'

    (Yo/) Nbar(g, h)O

    (Yi>) x B new (bar)'

    (Yo>) bar(g, h)

    (Yi8) xh B '

    (Yo8)

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    85/109

    (Yi8'

    (Yo8

    (Yi;) xh'

    (Yo;)

    (Yi5) xh B /0'

    (Yo5) /0

    (Yi) x'

    (Yo) bar(g, h /0)

    (Yi1) h'

    (Yo1) />8

    11

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    86/109

    10

    6.,ogic and *echniues

    Pro)ra* 9 data $tructure 6 al)orith*

    Al)orith* 9 lo)ic 6 controlA pro)ra* i$ a theory in $o*e lo)ic0 and co*putation i$ deduction fro* the theory.

    Lo)ic pro)ra**in) i$ characterized &y pro)ra**in) with relation$ and inference.

    :eyword$ and phra$e$;?orn clause, %ogic programming, inference, modus ponens,

    modus tollens, logic variable, unification, unifier, most general unifier, occurschec&,

    bac&trac&ing, closed world assumption, meta programming, pattern matching. set,

    relation, tuple, atom, constant, variable, predicate, functor, arity, term, compound term,

    ground, nonground, substitution, instance, instantiation, existential *uantification,

    universal *uantification, unification, modus ponens, proof tree, goal, resolvent.

    A logic program consists of a set of axioms and a goal statement. he rules of inference

    are applied to determine whether the axioms are sufficient to ensure the truth of the goal

    statement. he execution of a logic program corresponds to the construction of a proof of

    the goal statement from the axioms.

    In the logic programming model the programmer is responsible for specifying the basic

    logical relationships and does not specify the manner in which the inference rules are

    applied. hus

    %ogic # "ontrol Algorithms

    %ogic programming is based on tuples. Predicates are abstractions and generaliation of

    the data type of tuples. Eecall, a tuple is an element of

    = / ... n

    he s*uaring function for natural numbers may be written as a set of tuples as followsB

    X(=,=), (/,/), (>,,

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    87/109

    0=

    Abstracting to the name s*r and generaliing an individual tuple we can define the

    s*uaring relation asB

    s*r (x,x>)

    Parameteriing the name givesB

    s*r(D,R) _ R is Z DTD

    In the logic programming language Prolog this would be written asB

    s*r(D,R) _ R is Z DTD.

    Fote that the set of tuples is named s*r and that the parameters are D and R. Prolog

    does not evaluate its arguments unless re*uired, so the expression R is DTD forces the

    evaluation of DTD and unifies the answer with R. he Prolog code

    P _ .

    may be read in a number of ways' it could be read P where or P if . In this latter form

    it is a variant of the firstorder predicate calculus &nown as ?orn clause logic. A complete

    reading of the s*r predicate the point of view of logic isB for every D and R, R is the s*r of

    D if R is DTD. Hrom the point of view of logic, we say that the variables are universally

    *uantified. ?orn clause logic has a particularly simple inference rule which permits its use

    as a model of computation. his computational paradigm is called %ogic programming

    and deals with relations rather than functions or assignments. It uses facts and rules to

    represent information and deduction to answer *ueries. Prolog is the most widely

    available programming language to implement this computational paradigm.

    Eelations may be composed. Hor example, suppose we have the predicates, male(D),

    siblingof(D,R), and parentof(R,j) which define the obvious relations, then we can define

    the predicate uncleof(D,j) which implements the obvious relation as followsB

    uncleof(D,j) _ male(D), siblingof(D,R), parentof(R,j).

    he logical reading of this rule is as followsB for every D,R and j, D is the uncle of j, if

    D is a male who has a sibling R which is the parent of j. Alternately, D is the uncle of

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    88/109

    0/

    j, if D is a male and D is a sibing of R and R is a parent of j.

    Yfatherof(D,R),fatherof(R,j) defines paternalgrandfather(D,j)

    he difference between logic programming and functional programming may be

    illustrated as follows. he logic program

    f(D,R) _ R DT8#,8O,

    N8,,8O,

    Rs N8, and A=

    8 and 3 _ A=,AX/Z

    < infer k A= orZ k AX/Z

    ; choose k A=5 contradiction NO

    choose k AX/Z

    1 no further possibilitiesZ openZ

    here are two paths through the proof tree, /

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    95/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    96/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    97/109

    /==

    3y applying the inference rules to the program we derive the following additional *ueriesB

    [ b \wedge c . [ d \wedge c . [ e \wedge c. [ c. [

    Among the *ueries is an empty *uery. he presence of the empty *uery indicates that

    the original *uery is satisfiable, that is, the answer to the *uery is yes. Alternatively, the

    *uery is a theorem, provable from the given facts and rules.

    2nference and "nification

    GefinitionB he law of universal modus ponens says that from

    E (A B 3/,...,3n) and

    3/.

    ...

    3n.

    A can be deduced, if A B 3/,...,3n is an instance of E.

    GefinitionB A logic program is a finite set of rules.

    GefinitionB An existentially *uantified goal 4 is a logical conse*uence of a program P iff

    there is a clause in P with an instance A B 3/,...,3n, n \ge* = such that 3/,...,3n are

    logical conse*uences of P and A is an instance of 4.

    he control portion of the the e*uation is provide by an inference engine whose role is to

    derive theorems based on the set of axioms provided by the programmer. he inference

    engine uses the operations of resolution and unification to construct proofs.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    98/109

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    99/109

    /=>

    GefinitionB A is an instance of 3 if there is a substitution theta such that A 3theta.

    GefinitionB wo terms A and 3 are said to have a common instance " iff there are

    substitutions theta/ and theta> such that " Atheta/ and " 3theta>.

    A plus(=,8,R), 3 plus(=,D,D). " plus(=,8,8)

    since " AX R8Z and " 3X D8Z.

    GefinitionB A unifier of two terms A and 3 is a substitution ma&ing the two terms

    identical. If two terms have a unifer they are said to unify.

    p(a,D,t(j))theta p(R,m,)theta where theta X Dm,Ra,t(j) Z

    GefinitionB A most general unifier or mgu of two terms is a unifier such that the

    associated common instance is most general.

    unify(A,3) B unify/(A,3).

    unify/(D,R) B D R.

    unify/(D,R) B var(D), var(R), DR. Y he substitution

    unify/(D,R) B var(D), nonvar(R), \# occurs(D,R), DR. Y he substitution

    unify/(D,R) B var(R), nonvar(D), \# occurs(R,D), RD. Y he substitution

    unify/(D,R) B nonvar(D), nonvar(R), functor(D,H,F), functor(R,H,F),

    D ..NHSEO, R ..NHSO, matchlist(E,).

    matchlist(NO,NO).

    matchlist(NDSEO,N?SO) B unify(D,?), matchlist(E,).

    occurs(A,3) B A 3.

    occurs(A,3) B nonvar(3), functor(3,H,F), occurs(A,3,F).

    occurs(A,3,F) B F =, arg(F,3,AF), occurs(A,AF),J. Y ECG

    occurs(A,3,M) B M =, F is M /, occurs(A,3,F).

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    100/109

    +$%

    A )imple 2nterpreter for 0ure 0rolog

    An interpreter for pure Prolog can be written in Prolog.

    A simple interpreter for pure Prolog

    istrue( 4oals ) _ resolved( 4oals ).

    istrue( 4oals ) _ write( no ), nl.

    resolved(NO).

    resolved(4oals) _ select(4oal,4oals,Eestof4oals),

    Y 4oal unifies with head of some rule

    clause(?ead,3ody), unify( 4oal, ?ead ),

    add(3ody,Eestof4oals,Few4oals),

    resolved(Few4oals).

    prove(true).

    prove((A,3)) _ prove(A), prove(3). Y select first goal

    prove(A) _ clause(A,3), prove(3). Y select only goal and find a rule

    is the Prolog code for an interpreter.

    he interpreter can be used as the starting point for the construction of a debugger for

    Prolog programs and a starting point for the construction of an inference engine for an

    expert system.

    he operational semantics for Prolog are given in Higure\refXlpBopsemZ

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    101/109

    /=,8SDOQD,N

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    108/109

    111

    &. /onc"usion

    -ith the above study on principles of the programing languages, it is cleared that there

    are mainly six important basic principles. he principles are nothing but the basis or roots

    or sources. hey are not flexible. 3ut in the computing, the basics are also having the

    nature of flexibility and changing components to the stetted ob:ects. he 6b:ect 6riented

    Programming is innovated to meet the re*uired stetted targets. his promotes flexibility

    of general programming principles due to composite computing.

    As discussed above, a language should necessarily built with basic principles of itsprocedural and functional structures. he syntax,semantics,logic(s),data types are its

    ingredients. In fact these ingredients are all founding or building materials of the

    programing languages. A programming language should not rigid and should not over

    flexible. It should transforms and transport along with its ingredients towards

    programmers targets or ob:ects in the complex computing environment. his ob:ect was

    tried to discuss in the above chapters.

  • 8/12/2019 A Study on Fundamental Principles of Programming Languages

    109/109

    2eerences

    Programming %anguagesB Principles and Practices2enneth ". %ouden, Kenneth

    A. Lamber

    Programming languages-Allen B. Tucke

    Programming %anguage PragmaticsMichael %. cott >==0

    Practical Aspects of Geclarative %anguagesB />th International ymposium Manuel

    "arro, Ricardo Pea

    Mc*s In "omputer cience,>C-illiams >==;

    http://books.google.co.in/books?id=6MOiYFg1DoIC&printsec=frontcover&dq=principles+of+programming+languages&cd=6http://books.google.co.in/books?id=6MOiYFg1DoIC&printsec=frontcover&dq=principles+of+programming+languages&cd=6http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+C.+Louden%22http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+C.+Louden%22http://books.google.co.in/books?id=6MOiYFg1DoIC&printsec=frontcover&dq=principles+of+programming+languages&cd=6http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+A.+Lambert%22http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+A.+Lambert%22http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+A.+Lambert%22http://books.google.co.in/books?id=CnJRxnK92c4C&printsec=frontcover&dq=principles+of+programming+languages&cd=8http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Allen+B.+Tucker%22http://books.google.co.in/books?id=GBISkhhrHh8C&printsec=frontcover&dq=principles+of+programming+languages&cd=10http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Michael+L.+Scott%22http://books.google.co.in/books?id=GBISkhhrHh8C&printsec=frontcover&dq=principles+of+programming+languages&cd=10http://books.google.co.in/books?id=pArdWcRIr1AC&printsec=frontcover&dq=principles+of+programming+languages&lr=&cd=31http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?id=pArdWcRIr1AC&printsec=frontcover&dq=principles+of+programming+languages&lr=&cd=31http://books.google.co.in/books?id=pArdWcRIr1AC&printsec=frontcover&dq=principles+of+programming+languages&lr=&cd=31http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?id=MQmOP7GTxeoC&pg=PP10&dq=principles+of+programming+languages&lr=&cd=38http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Williams%22http://books.google.co.in/books?id=MQmOP7GTxeoC&pg=PP10&dq=principles+of+programming+languages&lr=&cd=38http://books.google.co.in/books?id=6MOiYFg1DoIC&printsec=frontcover&dq=principles+of+programming+languages&cd=6http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+C.+Louden%22http://books.google.co.in/books?id=6MOiYFg1DoIC&printsec=frontcover&dq=principles+of+programming+languages&cd=6http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+A.+Lambert%22http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Kenneth+A.+Lambert%22http://books.google.co.in/books?id=CnJRxnK92c4C&printsec=frontcover&dq=principles+of+programming+languages&cd=8http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Allen+B.+Tucker%22http://books.google.co.in/books?id=GBISkhhrHh8C&printsec=frontcover&dq=principles+of+programming+languages&cd=10http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Michael+L.+Scott%22http://books.google.co.in/books?id=GBISkhhrHh8C&printsec=frontcover&dq=principles+of+programming+languages&cd=10http://books.google.co.in/books?id=pArdWcRIr1AC&printsec=frontcover&dq=principles+of+programming+languages&lr=&cd=31http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?id=pArdWcRIr1AC&printsec=frontcover&dq=principles+of+programming+languages&lr=&cd=31http://books.google.co.in/books?q=principles+of+programming+languages&lr=&sa=N&start=30http://books.google.co.in/books?id=MQmOP7GTxeoC&pg=PP10&dq=principles+of+programming+languages&lr=&cd=38http://www.google.co.in/search?tbo=p&tbm=bks&q=inauthor:%22Williams%22http://books.google.co.in/books?id=MQmOP7GTxeoC&pg=PP10&dq=principles+of+programming+languages&lr=&cd=38