136
Computing Fundamentals 2 Lecture 3 Modern Algebra Lecturer: Patrick Browne http://www.comp.dit.ie/pbrowne/ [email protected] Lecture Room Based on Chapter 18. A Logical approach to Discrete Math By David Gries and Fred B. Schneider And CafeOBJ literature

Computing Fundamentals 2 Lecture 3 Modern Algebra Lecturer: Patrick Browne [email protected] Lecture Room Based on

  • View
    219

  • Download
    1

Embed Size (px)

Citation preview

Computing Fundamentals 2Lecture 3

Modern Algebra

Lecturer: Patrick Brownehttp://www.comp.dit.ie/pbrowne/

[email protected] Room Based on Chapter 18.

A Logical approach to Discrete Math By David Gries and Fred B. Schneider

And CafeOBJ literature

From the syllabus

• Algebraic Structures and Techniques: algebras, theories, models, composition, abstract data types (ADTs), languages for algebraic specification and programming, applications to lists, strings, queues (FIFO), stacks (LIFO), trees, etc.

• Algebraic structured need to be specified and implemented.

• The CafeOBJ language can be used for specification and implementation .

Modern Algebra

• In this lecture we look at:

• Structure of Algebra

• Algebraic Specifications

• Algebraic/functional programs

• Morphisms: how algebras are related

Algebraic Specifications• Algebraic specification is a formal process of defining and

refining specifications to develop correct information systems. Traditionally AS was used for the rather narrow task of ‘program specification’ newer AS systems can specify an entire information systems from ontology to database and code. Algebraic specifications can:

• 1. Represent mathematical structures and functions over those structures.

• 2. Provide an abstraction mechanism free from implementation details such as the size of representations (in memory) and the computational efficiency.

• 3. Permit automation due to a limited set of rules ( not over-specified).

• 4. Sets the scene for implementation of a prototype.

Modern Algebra

• Modern Algebra is the study of the structure of sets along with operations on those sets.

• An algebra is a model of a theory .• The formulas of a logic are often intended to be

statements about some domain of discourse (DOD). Formulas may be interpreted as having a meaning with respect to this DOD by defining which formulas are true statements and which statements are false about DOD.

• An interpretation assigns meaning to the operators, constants, and variables of a logic.

• We must distinguish between interpretation in a formal language and interpretation of a formal language.

Model Theory

• We distinguish between: – Syntax : of a formal logic/system – Semantics : the interpretation of a formal logic/system

• Last year we used truth tables to define operations and to evaluate expressions.

• Truth tables provide an interpretation (or meaning or model) for the Boolean expressions.

• An interpretation can have two parts:– A fixed meaning, based on operators and constants– A state based meaning, based on values of the variables.

• We say a model (an algebra or program) satisfies a theory (a set of axioms). Model Theory

Model Theory

• Models of computation versus models of the world.

Common model assumed

We must distinguish between interpretation in a formal language and interpretation of a formal language. Two distinct but related models.

Mapping between informal and formal domains

Model Theory (Sowa1)

Sound and complete.

• A logic is sound iff every theorem is valid

• A logic is complete iff every valid formula is a theorem.

Abstraction Process

In general the word model is overloaded (i.e. means more than one thing). It can mean a toy system. A miniature representation of an object. A pattern on which something not yet produced will be based. A design or type. Something serving as an example to be emulated or imitated. In model theory, a model must satisfy the axioms of the theory.

In model theory, a model must satisfy the axioms of the theory.

What is a model? Jackson(Jackson 1995) (page 121) advises against the mathematical use of the term model, where it is not applicable. Some mathematicians, logicians and computer scientists consider the real world as a model for their theories. But their conceptual framework is a world of Platonic abstraction removed from the world of real systems. He states: “How much faith would you place in a cartographer who told you that the world is a model for his map?”. If we contrast this with Frank (Frank 2003) statement: "Technically, the world and the information systems are models for the abstract behaviour described algebraically".

Modern Algebra

• Modern Algebra is the study of the structure of sets along with operations on those sets.

• An algebra is a model of a theory.• One Boolean algebra is the standard model (?)

for the propositional calculus. To see CafeOBJ’s BOOL module, type: show module BOOL

• We have studied quantification for commutative operations. (Chapter 8 last year). Another name for these operations and their sets is commutative or Abelian monoids. We also studied associative operations.

Structure of algebras

• An algebra consists of two components:– A set S of elements, called the carrier of the algebra.– Operators defined on the carrier set.

• Each operator is a total function Sm->S, where m is the arity of the operator, e.g. from River-Crossing op change : Side -> Side .

• Constants are considered as operators with an arity of null (nullary operators), e.g. from River-Crossing op right : -> Side

Structure of algebras

• An algebra has more structure than a set, i.e. the behaviour of the operations.

• A function has an arity– Number and sort* of arguments– Zero arity represent a constant– The rank is the number of elements in the arity.

• Co-arity: Sort of result

• Profile: the arity and coarity

Structure of algebras

• Some example operations from CafeOBJ:• if condition then c else d fi• Is a ternary function can be used in

CafeOBJ as follows1:• eq {X} \ S = if (X in S) then {} else {X} fi .

• Operators can be written in various forms prefix +(a,c) or infix a + b., or mixfix as above if_then_else_fi. In CafeOBJ underbars act as place holders.

BOOL + NAT example

• open BOOL + NAT• red if true then true else false fi .

• red if true then 6 else 7 fi .• red if true then false else 7 fi .

ERROR?

Specification of Natural Numbers

module SIMPLE-NAT { [ NzNat Zero < Nat ] op 0 : -> Zero op s_ : Nat -> NzNat op _+_ : Nat Nat -> Nat {assoc } vars M N : Nat eq 0 + N = N . eq N + s M = s(N + M) . }

Specification of Natural Numbers

module SIMPLE-NAT { [ NzNat Zero < Nat ] op 0 : -> Zero op s_ : Nat -> NzNat op _+_ : Nat Nat -> Nat {assoc } vars M N : Nat eq 0 + N = N . eq N + s M = s(N + M) . }

mod ARABIC-PEANO {pr(SIMPLE-NAT)ops 1 2 3 4 5 6 7 8 9 : -> NzNat eq 1 = s(0) . eq 2 = s(1) . eq 3 = s(2) . eq 4 = s(3) . eq 5 = s(4) . eq 6 = s(5) . eq 7 = s(6) . eq 8 = s(7) . eq 9 = s(8) . }

open ARABIC-PEANOred 3 + 4 . red 9 + 9 .

Using the reduce (red) command

• At operational level CafeOBJ's pattern matching modulo associativity or commutativity. For example, if we define

op _+_ : Nat Nat -> Nat {comm} vars M N : Nat eq M + 0 = M . eq M + s N = s(M + N). • The first equation can match 0 + (s s 0) and

the second can match (s x) + y, returning s s 0 and s(x + y), respectively. Matching modulo associativity and commutativity provides very powerful pattern matching.

Structure of algebras

• Some example operations from CafeOBJ:• 1 is function that takes no arguments and

always returns the value 1.• ops 1 2 3 4 5 6 7 8 9 : -> NzNat

• Algebras are models and are related by means of homomorphisms, that is, maps that preserve the algebra structure. A homomorphism between algebras is analogous to a function between sets.

Examples of Algebras

• The set of even numbers and the operator +. As the carrier set is infinite the algebra is called and infinite algebra.

• The set of even numbers and the operations multiplication and division is not an algebra because division is not a total function (division by 0 not defined) .

• In general <S, > denotes an algebra with carrier S and a list of operations , (PHI).

• The set {true,false} and operators ,, and ⌐ is a finite algebra. Written <Bool,,, ⌐ >

Algebras & CafeOBJ

• An algebra consists of two components:

• 1) A set S of elements, called the carrier of the algebra. These are called sorts in CafeOBJ. The syntax is [SortList]. The sorts in CafeOBJ are ordered by a subsort relation (<). Hence CafeOBJ can represent Order Sorted Algebras (OSA).

Algebras & CafeOBJ

• An algebra consists of two components:• 2)Operators defined on the carrier set S. Each

operator is a total function Sm->S, where m is the arity of the operator. Constants are considered as operators with an arity of null (nullary operators). Operations and constants in CafeOBJ are represented with the op keyword. The operations are defined in the axiom section with the keywords eq or ceq.

Order Sorted Algebra (OSA)1

• There are many examples where all items of one sort are necessarily also items of some other sort. Every natural number () is an integer (), and every integer is a rational (). We may write this symbolically

• Natural ≤ Integer ≤ Rational• In CafeOBJ this is written < but means ≤.• [ Natural < Integer < Rational ]• Associated with each sort name is a meaning, i.e.

semantic denotation, the sub-sort relations appear as set-theoretic inclusion.

Order Sorted Algebra (OSA)1

• An OSA provides rigorous model theoretic semantics for all the following features:

• Allows a partial ordering relation on the set of sorts.

• Supports abstract data types with multiple inheritance roughly in the sense of object oriented programming.

• Allows several forms of polymorphism sub-sort, parametric, and ad-hoc (overloading e.g. +)

• Allows partial operations as total on equationally defined “error supersorts”2.

Polymorphism in OSA

• Ad hoc polymorphism in its strongest sense indicates semantically unrelated uses, such as + for both integer addition and Boolean disjunction. Even in this case, both instances of + are associative, commutative, and have an identity element. The operations have similar properties. Ad-hoc polymorphism allows the same function name to be used for different operations on different types.

Polymorphism in OSA

• Multiple representation. In this cases the uses are related semantically, but their representations may be different. Multiple representation polymorphism is less ad-hoc than ad-hoc polymorphism, for example Polar and Cartesian coordinates.

Polymorphism in OSA

• Parametric polymorphism, such as the map function. Map must behave the same regardless the types or operations used. Another example is Stack.

• Ad hoc polymorphism allows different semantic functions and structures to use the same symbol name in different ways.

• Subsort polymorphism where the different instances of an operation symbol are related by inheritance (interpreted as subset inclusion) such that the result does not depend on the instance used, as with + for natural, integer, and rational numbers.

Parametric polymorphism

• Parametric polymorphism allows a set of different sorts to use a single definition of a function or a structure.

-- Single definition of list

mod! LIST(T :: TRIV) {

[ Elt.T < List ]

op nil : -> List

op __ : Elt.T List -> List }

-- List can be used by different sorts

red in LIST(INT) : 1 2 3 .

red in LIST(CHARACTER) : 'A' 'B' 'C' .

mod* TRIV { [ Elt ] }Built-in module TRIV

Ad hoc polymorphism

• Ad hoc polymorphism (AHP), or overloading, allows different unrelated functions to share the same name. The operations are disambiguated through the use of the sorts in each declaration. AHP is a mechanism for name reuse independently of any semantic relationship among names, e.g. “push a door” is a different use of “push” than “push element on stack”. Example on next slide.

Ad hoc polymorphism

-- The operation ++ doubles both arguments then adds

mod! DOUBLE-ADD {

Pr(INT)

op _++_ : Int Int -> Int

vars X Y : Int

eq X ++ Y = (X * 2) + (Y * 2)

}

-- CafeOBJ uses ++ to concatenate strings

-- to check this type show module STRING in CafeOBJ

-- ++ can be used by different unrelated sorts

red in DOUBLE-ADD : 1 ++ 3 .

red in STRING : “Ellen” ++ “Pat” .

Sub-sort Polymorphism

• Sub-sort polymorphism is a form of operator overloading that is consistent under sub-sort restriction. Operations defined in a super-sort can be used or redefined in the sub-sort. See example in next slide.

Sub-sort Polymorphismmod ADD2 {

pr(FLOAT) pr(INT)

-- Construct a sort hierarchy

-- This will identify the correct arguments for un-quantified digits and variables

[Int < Float]

vars i1 i2 : Int

vars f1 f2 : Float

op _++_ : Float Float -> Float

op _++_ : Int Int -> Int

op _++_ : Int Float -> Float

op _++_ : Float Int -> Float

}

open ADD2 .

-- If we use a sort hierarchy then OSA will ensure the correct sort on un-annotated digits

red 1 ++ 2 . **> gives Int

red 1 ++ 2.8 . **> gives Float

red 1.1 ++ 2 . **> gives Float

red 1.1 ++ 2.8 . **> gives Float

Quantified/Qualifying valuesopen INT .red 2:Nat .red 2:Int .red X:Int . Variables on the fly

OSA in CafeOBJ

Can be writen as: [ s4 < s2 s3 < s1][ s5 < s1 ]

Basic CafeOBJ

module <ModId> { signature { -- start of signature section[ <SortId> ] -- sort declarationop <OpForm> : <SortList> -> <Sort> -- operation declarationop <ConstName> : -> <Sort> -- constants are nullary operations.}axioms {var <VarId> : <Sort> -- variable declarationeq <Term> = <Term> . -- ordinary equationceq <Term> = <Term> if <Condition> . -- conditional equation-- Or transitions }}

CafeOBJ evaluationmodule SIMPLE-NAT {[ Zero NzNat < Nat ]signature {op 0 : -> Zeroop s : Nat -> NzNatop _+_ : Nat Nat -> Nat {comm, assoc}}axioms {var N : Natvar M : Nateq [0] : 0 + N = N .eq [1] : N + s(M) = s(N + M) . }}

red s(s(0)) + s(s(s(0)))Result: s(s(s(s(s(0)))))

A reduction in CafeOBJ.See next slide

CafeOBJ evaluation

Shows the process of term rewriting when the start term is “red s(s(0)) + s(s(s(0)))“ giving “s(s(s(s(s(0)))))" (showing that 2+3=5)Authors T. Ogawa and J. Tanaka

eq [0] : 0 + N = N . Note + is commutative eq [1] : N + s(M) = s(N + M)s(s(0)) + s(s(s(0))) s(s(s(s(s(0))))) start eq[1] eq[1] eq [1] eq [0] end

Signature

• The signature of an algebra consists of the name of its carrier set and a list of types of its operations.

signature { [ NzNat Zero < Nat ] op 0 : -> Zero op s_ : Nat -> NzNat op _+_ : Nat Nat -> Nat }

Signature

Maths Notation:

<B, B x B -> B, B x B -> B, B -> B>

CafeOBJ notation.signature {

[ true false ]

op _ and _ : Bool Bool -> Bool

op _ or _ : Bool Bool -> Bool

op not _ : Bool -> Bool

}

Signature

• Two algebras have the same signature (ignoring renaming) if they have the same number of operators and the corresponding operators have the same types modulo the name of the carrier. If we consider a signature as a sequence then:

• <Bool,,, ⌐ > : Boolean Algebra• <S,,, > : Set Theory• Have the same signature. While• <S,,,>• Does not have the same sig. (look at arities)

Properties (attributes) of operations

• Properties of certain constants wrt. some operation :– Identity (Unit): 1 b = b, b 1 = b– Zero: 0 b = 0 , b 0 = 0– Inverse: b RightInv = 1, LeftInv b = 1

• (18.5) Theorem: Let 1 be the identity of binary operator on S. Then b has a right inverse c wrt. and c has a left inverse b wrt. if b c = 1.

• Elements b and c are called inverses of each other if b c = c b = 1• E.g. b=3, c=1: 1x3=3, 3x1=3. identity 0x3=0, 3x0=0, zero 3x(1/3) = 1, (1/3)x3 = 1, inverse

Examples of inverses• In algebra of integers <,+>, 0 is an identity, for every b and there exists an inverse –b (where means +-Int).

• In the algebra of reals <,>, 1 is an identity, every element b (except 0) has an inverse ( real numbers).

• In general every one-to-one and onto function has an inverse. (18.6) Theorem: Let li be a left inverse and ri be a right inverse of element b with respect to operator . Then li=ri and b has unique inverse. In other words, if an operation has both a left and a right inverse then they are the same. We can check left and right inverse by showing

• li b = unit and b ri = unit.

Subalgebras

Operation

A

• A is a carrier set of some algebra. B is a

subset of A. We say B is closed wrt an

operation () if the operation returns a value in

B when its arguments are from B.

B

Subalgebras

• Algebras are differentiated by their structure. Structure refers to properties like the existence of an identity, but also refers to the kinds of sub-algebras an algebra has.

• (18.7) Definition: A subset T of a set S is closed under an operator if applying the operator to elements of T always produces a result in T

Example: Closed sub-algebras

• The set of even integers under + is closed because the sum of two even integers is an even integer.

• Subset T={0,1} of the integers is not closed under + because 1+1 is not in T.

• Subset T={0,1} of the integers is closed under max(x,y) because the max of any two is one of them.

Sub-algebra

• A sub-algebra satisfies all the properties of an algebra: T is non-empty and T is closed under operations. Note we can ‘overload’ function names e.g. f over T may be distinct from f over S (e.g. + for and + for ).

• Algebra <,+> is a sub-algebra of <,+> because and is closed under +

• Algebra <{1,0},+> is not a sub-algebra of <,+> because {0,1} is not closed under +

• Any algebra is a sub-algebra of itself. = Natural, Integer = Rational, = Real

Mappings (morphisms) between algebras

• Consider the function h:->+ that assigns every a to its absolute value |a| in +, the set of non-negative real numbers. Note, the function h relates carrier sets (sorts in CafeOBJ, types/classes in Python), h has the property that it is compatible with (or preserves) the multiplicative structure of because:

[eq1] |a * b| = |a| * |b| where a,b • We get the same result on either side of [eq1]. h is a

mapping between the carrier sets of two algebras, while * is an operation defined on both algebras. LHS * must handle a, b RHS does not.

Morphisms• Previously we looked at the internal structure of

algebras. Now we consider relating and structuring algebras (e.g. CafeOBJ’s imports and parameters, MDA1). When combing algebras, we need ways to characterize structural similarities between algebras.

• Do they look the ‘same’?• Could they be mapped to each other?• Three types of morphism:

– Isomorphism (equal shape)– Automorphism (self shape, not covered here)– Homomorphism (same shape, structure-preserving)

Morphisms

Def 18.9 Isomorphism (a)

• Isomorphic algebras are the same except for renaming1 of elements and operators.

• Algebras A, A’ have the same signature:A =<S, > and

A’ =<S’, ’>

• A function h:S->S’ is an isomorphism from A to A’ if:

• (a) Function h is one-to-one and onto.

Def 18.9 Isomorphism (b,c)

• (b) For each pair of corresponding nullary operators (constants) c in and c’ in ’, h.c=c’.

• (c) For each pair of corresponding unary operators in and ’ in ’, h(b)= ’h.b (for b in S).

Def 18.9 Isomorphism (d)

• (d) For each pair of corresponding binary operators in and ’ in ’, h(bc)= h.b ’ h.c (for b and c in S).

• Checking isomorphism between algebras involves checking properties (a-d) of Definition 18.9. with operation o, morphism h. The diagram commutes if:

• h(b c)= h.b ’ h.c (for b,c S)

• Note how the equation relates to the diagram

Isomorphism

Isomorphism

• Property 18.9 can be depicted as a commuting diagram. Each downward arrow represents an application of h to a value of S; the upper horizontal arrow represents application of to a value of SS. The lower horizontal line represents an application of ’ to a value of S’S’.

• The diagram commutes if:• h(b c)= h.b ’ h.c (for b,c S)

Isomorphism

h(b c)=h.b ’ h.c (for b,c S)

Algebra 1

Algebra 2

Def 18.13 Homomorphism (a)

• A homomorphism relaxes the requirements that h is one-to-one and onto (i.e. onto the first property (a) from previous iso. case is not required). Let algebras A =<S, > and A’ =<S’, ’> have the same signature. A function h:S->S’ is an homomorphism from A to A’ if:

• (a) For each pair of corresponding nullary operators (constants) c in and c’ in ’, h.c=c’.

Def 18.9 Homomorphism (b,c)

• (b) For each pair of corresponding unary operators in and ’ in ’, h(b)= ’h.b (for b in S).

• (c) For each pair of corresponding binary operators in and ’ in ’, h(bc)= h.b ’ h.c

• Informally, the homomorphism condition says that the behaviour of the operations in A is reflected in that of the operations in A’.

Homomorphism

• An ordinary function is a map from one set to another (last year’s course). A homomorphism is a map from one algebra to another algebra. An algebra is a set and the operations defined on that set. A homomorphism is a mapping which relates the sets underlying two algebras which preserves their structure (i.e. their operations).

Homomorphism

• Whenever you design data structures and procedures in a program you are constructing a homomorphism. For example, file names1 (or database tables) may represent sets of data, file manipulation operations may represent union, intersection, and membership relations. Records in programming languages represent Cartesian product.

• What exactly are the above example homomorphisms between? Between models, an implementation of a theory of sets can be mapped to files (ops merge files->set union, delete elements -> set difference)

Homomorphism f Syntactic world of signatures and

signature

morphisms

Semantic world of carrier sets and operations and homomorphisms

What is the mapping f ?

With a homomorphism h, f.S may be smaller than S, but the structure of the sets is similar wrt. properties of the operators because of the commutative nature of h, which is implied by definition

Isomorphism

{} {x}

{x} {x}

{} {x}

{}{x}

{} {}

{} {x}

{} {x}

{}{x}

T F

F F

T F

TF

T T

T F

T F

TF

Isorphism m: T {} , F {x}, which is compatible with, ,

Another morphism could be F {} , T {x}, which is compatible with, ,

Consider set {{},{x}} with operations and

Consider set {T,F} with operations and .

homomorphism• An isomorphism, is a homomorphism that

is also one-to-one and onto. Let h.S denote the range of function h:h.S With an isomorphism h, S and h.S have the same size. With a homomorphism h, h.S (target or range) may be smaller than S, but the structure of the sets is similar wrt. properties of the operators because of the commutative nature of h, which is implied by definition 18.13.

Homomorphism: examples

1) Function h.b=5 * b is a homomorphism from algebra <,+> to itself. There are no unary operators, and h(b+c) = 5*(b + c) = (5*b)+(5*c) = h.b + h.c

(for b, c in ). • In general, for any positive integer K,

including 0, h.b = k * b is a homomorphism from <,+> to itself.

Homomorphism: examples

2) Let be the function defined

bc=(b+c) mod 5.Then h.b=b mod 5 is a homomorphism

from <,> to <0..4,>In the first algebra <,> the arguments are

all of in the second case the algebra is <0..4,> and the carrier set is restricted to {0,1,2,3,4}

Homomorphism: examples

3) Homomorphism from sequences of characters (strings) to numbers: h:seq(char)-> defined by h.z=#z is a homomorphism <seq(char),^, > to <,+> (length of string).

• Where ^, is a concatenate operation (++ in CafeOBJ) and the symbol is the empty string (“” in CafeOBJ). See next slide.

Homomorphism: examples

• Consider the length function in CafeOBJ which takes a sequence of characters and returns their length a number.

• open STRING

• red length("123"): Result 3 : NzNat3

• STRING> red length("") : result 0 : Zero

• The concatenate operator ^ is ++ in CafeOBJ

• red length(“12” ++ “12”) .

Homomorphism: examples

red length("12"++"12")==length("12")+length("12")

-->(length("1212")==(length("12")+length("12"))

--> (4 == (length("12") + length("12")))

--> (4 == (2 + length("12")))

--> (4 == (2 + 2))

--> (4 == 4)

--> true.

Stack as a software object(LIFO)

Stack Code.1

class Stack :

def __init__(self) :

self.items = []

def push(self, item) :

self.items.append(item)

def pop(self) :

return self.items.pop()

def isEmpty(self) :

return (self.items == [])

Stack Signature (syntax)mod! STACK { imports { pr(BOOL) pr(NAT) } signature { [ Stack ] op zero : -> Nat op newstack : -> Stack op isnewstack : Stack -> Bool op push : Stack Nat -> Stack op pop : Stack -> Stack op top : Stack -> Nat }}

Stack Signature + Axioms signature { [ Stack ] op zero : -> Nat op newstack : -> Stack op isnewstack : Stack -> Bool op push : Stack Nat -> Stack op pop : Stack -> Stack op top : Stack -> Nat }}

axioms { var N : Nat var S : Stack eq isnewstack(newstack) = true . eq isnewstack(push(S,N)) = false . eq top(newstack) = zero . eq top(push(S,N)) = N . eq pop(newstack) = newstack . eq pop(push(S,N)) = S . }} run open STACK red isnewstack(push(newstack,1)) . red pop(push(newstack,1)) . red push(push(newstack,2),3) . red top(push(push(newstack,3),6)) .

The signature alone does not capture the “last in first out” (LIFO) property of a stack. We need to add axioms to establish that.

Generic Stacks

At signature level the pushout1 concept can be used to combine algebras (more later).

Syntax can be related to semantics

• In general we prove logical consequences by using syntax (not semantics or models)

• The proof usually relies on some logic (e.g. propositional logic). If the logic is sound then a result proved syntactically is assumed to be true semantically.

• We use a denotation function to relate syntax to semantics.

Denotation Function

• If sorts are mapped to carrier sets then each named operation in the signature should mapped to a total function in the algebra. To formally relate a signature to an algebra we will use the denotation function from VanHorebeek and Lewi (Horebeek and Lewi 1989). We can take terms from the signature (which is syntax denoted ∑) and map them to the semantic domain. For example:

.newstack .Stack .push(newstack,zero) .Stack

Denotation Function

Nat

Stack

Bool

Initial Algebra

Signatures & Algebras

• The many-to-many relation between signatures (∑) and algebras (or models):

• The signature NAT denotes the algebra consisting of the set of natural numbers denoted by the sort Nat and the successor function.

mod! NAT { [ Nat ] op zero : -> Nat op succ : Nat -> Nat }

mod! N { [ Nat ] op zero : -> Nat op next : Nat -> Nat }-- a mapping from N signature to algebra

.Nat = Nat

.succ = succ

.zero = 0

Signatures & AlgebrasNat

Morphisms

• Two algebras may be related by a homomorphism or an isomorphism. A homomorphism from algebra A to algebra B with respect to a given signature is a family {f1, f2, ,f3 …,f1} of mappings in which each fj is a mapping from the set A.Sj of objects of sort Sj in algebra A onto the set B.Sj of objects of sort Sj in algebra B. The behaviour of the operations must be preserved by the family of mappings. A bijective homomorphism is called an isomorphism.

Morphisms

• As examples we will consider one homomorphism and one isomorphism using the signatures in the next few slides. The two algebras are NAT and MOD2. The algebra NAT consists of the set of natural numbers and the successor function. The algebra MOD2 consists of the set of numbers modulo 2 and the addition-modulo-2 function denoted by add2().

MOD2

The algebra MOD2 consists of the set of {1, 0}numbers modulo 2 and the addition-modulo-2 function denoted by add2(0)=1, add2(1)=0.

Homomorphism

NAT

MOD2

Isomorphism

Algebra of Arabic numbers

Algebra of binary numbers

Parameterised specification

The pushout1 concept can be used to combine algebras (more later).

Parameterised specification

Parameterised specification

open STACK(INT)open STACK(STRING)open STACK(CHARACTER)

Morphisms in practice (views)

• Views in CafeOBJ specify homomorphisms between modules. In CafeOBJ a view describes the association between a theory (mod*) and an object (mod!), such that the sorts of the theory is mapped to the sorts of the objects while preserving the sub-sort relation (OSA). The operations of the theory are mapped to the operations of the object.

• In CafeOBJ a view is a homomorphism from the algebra described by the theory to the algebra described by the object.

• H : Theory -> Object

Morphisms in practice (views)

• In CafeOBJ modules can represent an abstract theory (mod*) or an executable (in programming sense) object (mod!) . In CafeOBJ both theories and objects can be executed by a term rewriting system (TRS). A theory defines properties that may be satisfied by another theory or object. A view is mapping between a theory and a module (which can be another theory or an object).

Morphisms in practice (views)

• In CafeOBJ a view describes the association between a theory (mod*) and an object (mod!), such that the sorts of the theory is mapped to the sorts of the objects while preserving the sub-sort relation. The operations of the theory are mapped to the operations of the object.

• A view represents a homomorphism from the algebra described by the theory to the algebra described by the object.

• To instantiate a parameterized module is to replace the parameters with modules that satisfy the syntactic and semantic constraints.

Morphisms in practice

• The simplest (builtin) theory is TRIV, which represents any set, with no operations.

mod* TRIV {

[ Elt ]

}

Morphisms in practice• TRIV can be used as a parameter to a module. It can be

considered as a set with no operations. mod! POSET (X :: TRIV){pr(BOOL)op _<=_ : Elt Elt -> Boolop _=P=_ : Elt Elt -> Boolvars X Y Z : Elteq X <= X = true .eq X =P= X = true .eq (X <= Y) and (Y <= X) = X =P= Y .eq (X <= Y) and (Y <= Z) = X <= Z .}

Morphisms in practice• Instantiation of parameterized module replaces its formal

parameters with an actual parameters. Each theory is replaced by the corresponding actual module of the formal parameters. See how NAT replaces TRIV after Instantiation (a view from theory TRIV to object NAT).

open POSET(NAT) show modulemodule POSET(X <= NAT){protecting (NAT)pred _ =P= _ : Nat Nat eq (X:Nat <= X) = true .eq (X:Nat =P= X) = true .eq ((X:Nat <= Y:Nat) and (Y <= X)) = (X =P= Y) .eq ((X:Nat <= Y:Nat) and (Y <= Z:Nat)) = (X <= Z) .}

Some mathematical structures

• A set with a total associative operation is called a semigroup

• A semigroup with an identity element is called a monoid.

• A monoid in which every element has an inverse is called a group.

Morphisms in practice

mod* MONOID {

[ M ]

op e : -> M .

op _|_ : M M -> M { assoc id: e}

}

Morphisms in practice

view NAT+ from MONOID to NAT

{sort M -> Nat, op _|_ -> _+_,op e -> 0}

view NAT* from MONOID to NAT

{sort M -> Nat, op _|_ -> _*_, op e -> 1}

Morphisms in practice

mod! FOLD[M1 :: MONOID] {

pr(LIST[M1])

op fold : List -> M

var X : M

var L : List

eq fold(nil) = e .

eq fold(X L) = X | fold(L) .

}

Example: Morphisms in CafeOBJ

• 1)In general a homomorphism is a structure-preserving mapping from one algebra to another. CafeOBJ refines this general idea in two ways:

• 2) A signature morphism is a structure-preserving mapping from a signature to another (e.g. MONOID to NAT using ‘view’ ). A signature morphism maps a signature to a signature, specifying a mapping of sorts and operators.

• 3) A specification morphism is a signature morphism where the translated axioms of the source algebra (MONOID) hold in the target algebra (NAT).

• NAT+ is a signature morphism mapping from the abstract MONOID to the concrete NAT (natural numbers), that induces a specification morphism.

CafeOBJ example of parameterized specification1

mod* POSET {[ Elt ]pred _<=_ : Elt Eltvars E1 E2 E3 : Elt

eq E1 <= E1 = true .cq E1 = E2 if (E1 <= E2) and (E2 <= E1) .cq (E1 <= E3) = true if (E1 <= E2) and (E2 <= E3) . }

mod! STRG (P :: POSET){[ Elt < Strg ]op nil : -> Strgop . : Strg Strg -> Strg { assoc }eq nil . S:Strg = S .eq S:Strg . nil = S .}

CafeOBJ example of parameterized specification1

• In general, views interpret the abstract parameter of a specification as a more concrete specification such that the models of the concrete specification realizes or implements the abstract specification.

view nat-poset from POSET to NAT {

sort Elt -> Nat,

op (E1:Elt <= E2:Elt) ->

((E1:Nat < E2:Nat) or (E1 == E2))}

• The strings over ordered naturals are then obtained by the instantiation, can be written:

STRG(P <= nat-poset) or STRG(nat-poset)

CafeOBJ example of parameterized specification1

• dotted arrows represent views,• unlabelled arrows represent imports, • labeled arrows for parameters.STRG(P <= view to NAT { sort Elt -> Nat,

op (E1:Elt <= E2:Elt) -> (E1:Nat < E2:Nat) or

(E1 == E2) })

Attributes for Operations

The above attributes are regarded as attributes of operations and define an equivalence relation among terms. Purpose: They help reduce the number of equations that need to be written by the user. They also help CafeOBJ rules to more closely resemble mathematical equations, e.g. if a + b = b + a. They increase the expressive power of CafeOBJ.

Example: Operation attributes in CafeOBJ

• Associativity holds when two an infix operations is performed on three arguments as follows: Arg1 op Arg2 op Arg3. We get the same value whether we start at the left or the right. For example, the Associative Law holds in Boolean Algebra.

• (A and B) and C=A and (B and C), and• (A or B) or C=A or (B or C)• The identity of an infix operation is an argument that

always returns the other argument: Arg1 op Arg1. Many algebras have an identity operation e.g. 1 for multiplication and 0 for addition. Both associativity and identity are used in CafeOBJ to describe properties of operations. CafeOBJ inserts the necessary axioms to enforce (or implement) the particular property.

Morphisms in practice

red in FOLD[NAT+]: fold(1 2 3 4) .

**> should be 10

red in FOLD[NAT*]: fold(1 2 3 4) .

**> should be 24

When actual arguments are supplied to modules we have another morphism from supplied argument (e.g NAT+) to object in the FOLD module (e.g. Nat -> M)

Group Theory

• Semigroups

• Monoids

• Groups

Semigroup

• A semigroup is an algebra <S, > , where is a binary (arity=2) associative operator. Examples:

• <S, ^> , is a simigroup, where S is the set of finite strings over an non-empty alphabet and ^ is string catenation.

• <{b,c},> , is a finite simigroup, where is defined as bb=cb=b and bc=cc=c

SIMIGROUP

mod* SEMIGROUP { protecting(TRIV) op _+_ : Elt Elt -> Elt {assoc} }

mod* SG-HOM (S1 :: SEMIGROUP, S2 :: SEMIGROUP) {

op h : Elt.S1 -> Elt.S2 vars X Y : Elt.S1 eq h(X + Y) = h(X) + h(Y) . }

Monoid

• A monoid <S,,1> is a semigroup <S, > with an identity 1. If is also symmetric then the monoid is called Abelian.

• Groups can be considered more sophisticated than a monoid in so far as there are more possible theorems in a group that in a monoid.

• Groups have extra rules to enforce the fact that every element should have an inverse.

• Thus, we can have a homomorphism from Monoid to a Group but not from a Group to a Monoid.

• In general the co-domain of a homomorphism is smaller than the domain. There are at least as many assertions to be made about the co-domain (possible more)

Monoid

mod* MONOID {

[ M ]

op e : -> M

op _*_ : M M -> M {assoc id:e }

}

Group

module* GROUP { [ G ] op 0 : -> G op _+_ : G G -> G { assoc } op -_ : G -> G var X : G eq 0 + X = X . eq (- X) + X = 0 . }

Interactive proof: Right Inverse

module* GROUP {[ G ] op 0 : -> G op _+_ : G G -> G { assoc } op -_ : G -> G var X : G eq [EQ1] : 0 + X = X . eq [EQ2] : (- X) + X = 0 . }

red (-X) + X . Gives 0red X + (- X) . Does not rewrite

Manual proof: Right Inverse• We want to prove that –X is a right inverse of +. A

standard proof goes as follows:1. X + (-X) < reverse of EQ1 >2. 0 + X + (-X) < reverse of EQ2 and negation >3. (-(-X)) + (-X) + X + (-X) < EQ2 >4. (-(-X)) + 0 + (-X) < EQ1 >5. (-(-X)) + (-X) < EQ2 >6. 0

eq [EQ1] : 0 + X = X . eq [EQ2] : (- X) + X = 0 .

Interactive proof: Right Inverse

• open GROUP • op a : - > G . -- a constant• start a + ( -a) . -- the term• apply -.EQ1 at (1) . • apply -.EQ2 with X = -a at [1] .

• apply reduce at term .

Homomorphism example : set

• D={{},{a},{a,b}}• E={{},{b},{a,b}}

E D

{} {}

{b} {a}

{a,b} {a,b}

Homomorphism example

• D ={{},{a},{a,b},{,}}• E ={{},{b},{a,b},{,}}• k(|E|)={{},{a}}• k(E)=<{{},{a}},{a,b},{,}> E D k(E)

{} {} {}

{b} {a} {a}

{a,b} {a,b}

Algebras and lattices

mod ARITHMATIC {[ Zero ][ Bottom < Neg < Pos < Real ]op _+_ : Neg Neg -> Negop _+_ : Pos Pos -> Posop _*_ : Neg Pos -> Negop _*_ : Neg Neg -> Posop _/_ : Real Real -> Real op _/_ : Real Zero -> Real

var X : Realeq X / X :is Pos = true .eq X * X :is Pos = true .}

Another Examplemod! LIST {pr(TRIV)pr(NAT)[Nat < Elt < NeList < List ] op nil : -> List op _,_ : List List -> List {assoc id: nil} }

mod* FUN {pr(TRIV)op f_ : Elt -> Elt }

mod! MAP(F :: FUN){pr(LIST)op map_ : List -> Listvar N : Eltvar L1 : Listeq map nil = nil . eq map (N , L1) = (f N ) , (map L1) . }

Another Example

mod! EVEN {

pr(LIST)

op even_ : Nat -> Nat

var N : Nat

ceq even N = N if (N rem 2 == 0) .

ceq even N = nil if (N rem 2 =/= 0) .

}

Another Example

view ME from FUN to EVEN

{sort Elt -> Nat, op f_ -> even_ }

make MAP-even ( MAP(ME) ) .

Another Example

red in MAP-even : map (0 , 1 , 2 , 3 , 4 , 5 , 6) .

Conclusion

• An algebra consists of two components:• 1) A set S of elements, called the carrier of the algebra.• 2) Operators defined on the carrier set S.• Which can be represented in CafeOBJ as follow:• 1) The set S of elements are called sorts in CafeOBJ.

The sorts in CafeOBJ are ordered by a subsort relation ( [S1 < S2] ). Hence CafeOBJ can represent Order Sorted Algebras (OSA).

• 2) Operators defined on the carrier set S. Each operator is a total function Sm->S, where m is the arity of the operator. Constants are considered as operators with an arity of null (nullary operators). Operations and constants in CafeOBJ are represented with the ‘op’ keyword.

Conclusion

• 1) A signature morphism is a structure-preserving mapping from a signature to another (e.g. FUN to DOUBLE using ‘view’). A signature morphism maps a signature to an other signature, specifying a mapping of sorts and operators in a way which makes ‘sense’..

• 2) A specification morphism is a signature morphism where the axioms of the source algebra (e.g. FUN) hold in the target algebra (e.g. DOUBLE).

• NAT+ is a signature morphism mapping from the abstract MONOID to the concrete NAT (natural numbers). In general a homomorphism is a structure-preserving mapping from one algebra to another. CafeOBJ refines this general idea in two ways with signature and specification morphisms.

Conclusion

• In CafeOBJ attributes can be attached to operations in CafeOBJ. The attributes help reduce the number of equations that need to be written by the user. They also help CafeOBJ rules to more closely resemble mathematical equations, e.g. a + b = b + a. Operation can have the following attributes:

• Associative: (a + b) + c = a + (b + c)• Commutative: a + b = b + a• Idempotent: x op x = x• Identity: x + 0 = x (or x + identity of + = x)

Conclusion

• Let A=<T,+> be an algebra, where T ={2,4}.

• A is not closed because 2 + 4 = 6 T.• Let B=<T,*> be an algebra, where T={1,0} and the * represents the multiply operation. B is closed under the multiplication (*) operation because 1 * 1 = 1 T1 * 0 = 0 T0 * 0 = 0 T

Conclusion

• FUN is a module that imports CafeOBJ’s predefined natural numbers.

• It declare one pre-fix operation called f_, takes a natural number and returns a natural number. Only the signature is declared no axioms are defined for f.

• MAP is a module that takes FUN as a parameter. It imports LIST. It fully defines a higher order1 function called map.

• The function map takes a list and produces an new list in which the function f is applied to every element of the new list.

Conclusion

• FUN is a module that imports CafeOBJ’s predefined natural numbers.

• It declare one pre-fix operation called f_, takes a natural number and returns a natural number. Only the signature is declared no axioms are defined for f.

• MAP is a module that takes FUN as a parameter. It imports LIST. It fully defines a higher order1 function called map.

• The function map takes a list and produces an new list in which the function f is applied to every element of the new list.

Conclusion

• 8. eq map nil = nil . • 9. eq map (N , L1) = (f N ) , (map L1) .

• Lines 8 and 9.• Line 8 says that a empty (nil) list produces an

empty list.• Line 9 says that if a list has a head element (N)

and a tail list (L1) then the function f should be applied to N and it should be added using the list constructor ‘,’ to the recursive call of map to the tail of the list.

Conclusion

view MD from FUN to DOUBLE {sort Elt -> Nat, op f_ -> double_ } .

make MAP-double (MAP(MD)) . • The view command creates a view called MD

from FUN (abstract) to DOUBLE (concrete) module. The view maps the abstract f function to the concrete double function. The make command makes an executable module, called MAP-double, from MAP and the view MD. MD matches the FUN module which is the parameter to MAP.

Object Orientation

• Principle OO concepts are: encapsulation, inheritance, polymorphism, and abstraction.

• Encapsulation hides internal structure of a class. Hiding internal state is called data encapsulation

• A subclass inherits all the members (fields, methods, and nested classes) from its superclass (constructors not inherited).

• Any message to which objects of more than one class can respond is said to be polymorphic.

• Abstraction suppresses detail, it provides representation independence

CafeOBJ sorts & Java Classes

• CafeOBJ sorts and Java classes are language techniques for organizing data and programs. There is not an exact mapping between CafeOBJ sorts and Java classes. However, we can compare the hierarchies that can be constructed using these language techniques.

CafeOBJ sorts = Java Classes

• Both techniques permit the super and sub relations.

• Both techniques specify sets of objects or instances.

• Both techniques support polymorphism.

CafeOBJ sorts =/= Java Classes

• CafeOBJ sorts permit multiple inheritance (only interfaces provide multiple inheritance in Java).

• Java classes enforce encapsulation. CafeOBJ modules rather than sorts encapsulate executable code.

CafeOBJ Shapesmod* SHAPES {pr(FLOAT) -- A list of shapes[ Shape < ShapeList ] op _,_ : Shape ShapeList -> ShapeList op nilShape : -> ShapeList

-- A list of areas[ Float < FloatList ]op _,_ : Float FloatList -> FloatList op nilFloat : -> FloatList

-- A generic list for shapes and areas[FloatList ShapeList < List ]

-- Data sort Shape and sub-sorts[Ellipse Rectangle < Shape ]-- The shape constructorsop rectangle__ : Float Float -> Shape {constr}op ellipse__: Float Float -> Shape {constr}

-- The area functionvars width height radius : Floatop area_ : Shape -> Float-- Area equations for each sorteq area (rectangle width height) = width * height .eq area (ellipse width height) = (pi * width * height) / 4.0 .

-- A function to loop through a list of shapes and construct a list of their areas.op for_ : List -> Listvar object : Shape var argList : ShapeListvar resList : FloatListeq for nilShape = nilFloat .eq for (object , argList) = (area object) , (for argList) . }

open SHAPE-OPSlet r = rectangle 5.0 8.0 .let u = ellipse 3.0 4.0 .red for (r , u , nilShape) .

Java Shapes/* From Semiotics of Programming: Kumiko Tanaka-Ishii*/ class ShapeProg { abstract class Shape{ double width, height; Shape(double w, double h) { width = w; height=h;} public double area() { return width * height; } }

class Rectangle extends Shape{ Rectangle(double w, double h) { super(w,h);} }

class Ellipse extends Shape{ Ellipse(double w, double h){ super(w,h);} public double area(){ return (Math.PI* width * height) / 4.0;} }

class Circle extends Ellipse{ Circle(double r){ super(r * 2, r * 2);}}

void putStr(String s){ System.out.print(s);}

void run() {Rectangle r = new Rectangle(5.0,8.0);Ellipse u = new Ellipse(3.0,4.0);Circle v = new Circle(3.0);Shape [] ss = new Shape [] {r, u, v};for (Shape s : ss) {putStr("area: " + s.area() + "\n");}}

public static void main(String[] args){ (new ShapeProg()).run();}}/* Outputarea: 40.0area: 9.42477796076938area: 28.274333882308138*/