error example - 65/4; ! toplevel input: ! 65/4; ! ^^ ! type clash: expression of type ! int ! cannot...

26
Error Example Error Example - 65/4; - 65/4; ! Toplevel input: ! Toplevel input: ! 65/4; ! 65/4; ! ^^ ! ^^ ! Type clash: expression of type ! Type clash: expression of type ! int ! int ! cannot have type ! cannot have type ! real ! real

Upload: estella-randall

Post on 08-Jan-2018

214 views

Category:

Documents


1 download

DESCRIPTION

Type Examples fun cast (n:int) = n; fun cast (n:int) = n; fun cast n = n : int; fun cast n = n : int; fun cast n = n+”abc”; fun cast n = n+”abc”; fun cast (n:int) = n+”abc”; fun cast (n:int) = n+”abc”;

TRANSCRIPT

Page 1: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Error ExampleError Example- 65/4; - 65/4; ! Toplevel input: ! Toplevel input: ! 65/4; ! 65/4; ! ^^ ! ^^ ! Type clash: expression of type ! Type clash: expression of type ! int ! int ! cannot have type ! cannot have type ! real ! real

Page 2: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Currying ExampleCurrying Example• Difference with left binding functionsDifference with left binding functions

– exp x y-1 exp x y-1 (exp x y) -1 (exp x y) -1– exp x (y-1)exp x (y-1)

- fun exp x y = if (y=0) then 1 else x * (exp x (y-1)); - fun exp x y = if (y=0) then 1 else x * (exp x (y-1)); > val exp = fn : int -> int -> int > val exp = fn : int -> int -> int

Page 3: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Type ExamplesType Examples• fun cast (n:int) = n;fun cast (n:int) = n;• fun cast n = n : int;fun cast n = n : int;• fun cast n = n+”abc”;fun cast n = n+”abc”;• fun cast (n:int) = n+”abc”;fun cast (n:int) = n+”abc”;

Page 4: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Polymorphic FunctionsPolymorphic Functions- fun id x = x; - fun id x = x; > val id = fn : 'a -> 'a > val id = fn : 'a -> 'a

- fun cond c x y = if c then x else y; - fun cond c x y = if c then x else y; > val cond = fn : bool -> 'a -> 'a -> 'a > val cond = fn : bool -> 'a -> 'a -> 'a

Page 5: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

the Let Functionthe Let Function- fun prodSum x y = (x+y) * (x+y); - fun prodSum x y = (x+y) * (x+y); > val prodSum = fn : int -> int -> int > val prodSum = fn : int -> int -> int

- fun prodSum x y = - fun prodSum x y = let let val sumXY = x + y val sumXY = x + y in in sumXY * sumXY sumXY * sumXY

end ;end ; > val prodSum = fn : int -> int -> int > val prodSum = fn : int -> int -> int

Page 6: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Tuple ExtractionTuple Extraction- let - let

val (u,v) = incBoth (3,5) val (u,v) = incBoth (3,5) in in

u u end; end; > val it = 4 : int > val it = 4 : int

Page 7: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

The Map FunctionThe Map Function- fun map f inpList = - fun map f inpList =

case inpList of case inpList of [] => [] [] => []

| (h::t) => (f h) :: (map f t) | (h::t) => (f h) :: (map f t) ; ;

> val map = fn : ('a -> 'b) -> 'a list -> > val map = fn : ('a -> 'b) -> 'a list -> 'b list 'b list

Page 8: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

The Filter FunctionThe Filter Function- fun filter condition inpList = - fun filter condition inpList =

case inpList of case inpList of [] => [] [] => []

| (h::t) => | (h::t) => if (condition h) if (condition h) then h :: (filter condition t) then h :: (filter condition t) else filter condition t else filter condition t

; ; > val filter = fn : ('a -> bool) -> 'a list -> 'a > val filter = fn : ('a -> bool) -> 'a list -> 'a

list list

Page 9: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Programming in MLProgramming in ML

By Drew WyborskiBy Drew Wyborski

Page 10: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Data Type/OperatorsData Type/Operators• Operators and types similar to Operators and types similar to

C++/JavaC++/Java– int, string, bool and real remain the sameint, string, bool and real remain the same– Operators have slight differencesOperators have slight differences

• Additional Boolean types are included Additional Boolean types are included showing the rational/logical basisshowing the rational/logical basis– andalso & orelseandalso & orelse

Page 11: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

SyntaxSyntax• Input is placed into user’s implementationInput is placed into user’s implementation• Machine responds with result of expressionMachine responds with result of expression• Specified layout for entry and outputSpecified layout for entry and output

– 3 + 4;3 + 4;– val it = 7 : intval it = 7 : int

• If an If an errorerror is made in entry, the machine is made in entry, the machine responds with an appropriate errorresponds with an appropriate error

• The unit data typeThe unit data type

Page 12: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

DefinitionsDefinitions• Global constantsGlobal constants

– val PI = 3.4;val PI = 3.4;– Help increase readabilityHelp increase readability

• FunctionsFunctions– fun succ n = n+1;fun succ n = n+1;– val succ = fn : int val succ = fn : int int int– Differences in calling compared to imperativeDifferences in calling compared to imperative

• ExtensionsExtensions– if…then…else functionsif…then…else functions– Multiple input/output functionsMultiple input/output functions

Page 13: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

CurryingCurrying• An extension of function writingAn extension of function writing• Special ability of functional languageSpecial ability of functional language• Left bindingLeft binding• Partial evaluation (aka “currying”)Partial evaluation (aka “currying”)• ExampleExample

Page 14: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

““Side-effect Free” Side-effect Free” ProgrammingProgramming• The interaction of functions in MLThe interaction of functions in ML• The use of referential-transparency occurs through The use of referential-transparency occurs through

the elimination of some imperative-type features:the elimination of some imperative-type features:– Global variablesGlobal variables– AssignmentsAssignments– Value-result parametersValue-result parameters– PointersPointers

• Advantages in readability and modification in small Advantages in readability and modification in small components or functionscomponents or functions

• Victims of elimination of side-effectsVictims of elimination of side-effects

Page 15: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Exceptions to Referential Exceptions to Referential TransparencyTransparency• Input/Output devicesInput/Output devices

– Something outside the program is changedSomething outside the program is changed– The functions have type that returns unitThe functions have type that returns unit

• Functions because the result must be Functions because the result must be expressed outside the interpreterexpressed outside the interpreter

• The print functionThe print functionprint “Hello there \n”;print “Hello there \n”;Hello thereHello there> value it = ( ) : unit> value it = ( ) : unit

Page 16: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Basic Syntactical NotesBasic Syntactical Notes• There is the option for expression There is the option for expression

sequencingsequencing• The use of sequencing leads to the The use of sequencing leads to the

loss of previous expressions unless loss of previous expressions unless they have the rare side-effect (most they have the rare side-effect (most likely “print”)likely “print”)

• Comments are important as in any Comments are important as in any other languageother language– Denoted through the use of (* … *)Denoted through the use of (* … *)

Page 17: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Type InferenceType Inference• Strength of ML that helps offset loss of Strength of ML that helps offset loss of

imperative functionsimperative functions• Ability to declare or not declare data Ability to declare or not declare data

typetype– Encouraged to do so for documentationEncouraged to do so for documentation– Similar notation to what we’ve already seenSimilar notation to what we’ve already seen– Allow us to make the implementer operate Allow us to make the implementer operate

correctlycorrectly– Help to clear up possible Help to clear up possible error messageserror messages

Page 18: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

PolymorphismPolymorphism• ML exhibits a strong amount of ML exhibits a strong amount of

polymorphismpolymorphism– Exists in function calls and data typingExists in function calls and data typing– Gives us the ability to openly code for many Gives us the ability to openly code for many

different data typesdifferent data types– Can create data variablesCan create data variables

• Some Some common polymorphic functionscommon polymorphic functions• Different notationDifferent notation associated with associated with

polymorphic functionspolymorphic functions

Page 19: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Higher-Order FunctionsHigher-Order Functions• Used to compact functions togetherUsed to compact functions together• Useful to extend an already defined Useful to extend an already defined

functionfunction• Helps add levels of abstractionHelps add levels of abstraction• Another example of the Another example of the

polymorphism present in MLpolymorphism present in ML

Page 20: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Function ExtensionFunction Extension• We are able to define some “local variables” We are able to define some “local variables”

through the use of the let functionthrough the use of the let function– This allows us to temporarily assign a value of This allows us to temporarily assign a value of

something to be used later in the expressionsomething to be used later in the expression– It is only good for the part of the statement It is only good for the part of the statement

enclosed in let expressionenclosed in let expression– Cannot use the let expression to try and mimic Cannot use the let expression to try and mimic

imperative assignment statementsimperative assignment statements• We can also use functions in this statementWe can also use functions in this statement

Page 21: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

Function ExtensionFunction Extension• There are some good guidelines that are There are some good guidelines that are

almost universal in writing longer almost universal in writing longer functions in ML:functions in ML:– Name the function and parameters on line 1Name the function and parameters on line 1– Indent the body of the function like you Indent the body of the function like you

would in Java or C++would in Java or C++– Include the terminating end; portion on its Include the terminating end; portion on its

own line at the endown line at the end

Page 22: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

TuplesTuples• Consist of pieces of data grouped Consist of pieces of data grouped

together in parenthesistogether in parenthesis– (3,4) or (“abc”,1) or (true,”abc”,87.4)(3,4) or (“abc”,1) or (true,”abc”,87.4)

• We can use tuples across functions We can use tuples across functions just like any other data typejust like any other data type

• To extract individual pieces of data To extract individual pieces of data from the tuple we utilize the let from the tuple we utilize the let functionfunction

Page 23: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

RecordsRecords• Similar to tuples except with names Similar to tuples except with names

for the componentsfor the components• Enclosed in a set of brackets with Enclosed in a set of brackets with

field=value components inside for field=value components inside for definitiondefinition

• They are then accessed through the They are then accessed through the use of the # function and then the use of the # function and then the field namefield name

Page 24: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

ListsLists• Lists are created through the construction of Lists are created through the construction of

data values between brackets of the same data values between brackets of the same typetype– [1,2,3] or [“ab”,”cd”,”ef”][1,2,3] or [“ab”,”cd”,”ef”]

• Things can be appended using ::Things can be appended using ::– 5 :: [1,2,3] 5 :: [1,2,3] [5,1,2,3] : int list [5,1,2,3] : int list

• Concatenation is done using the @ symbolConcatenation is done using the @ symbol– [1,2,3] @ [4,5,6] [1,2,3] @ [4,5,6] [1,2,3,4,5,6] : int list [1,2,3,4,5,6] : int list

• When using functions with lists we use the When using functions with lists we use the case operatorcase operator– This provides us with operations for an empty list This provides us with operations for an empty list

as well as one with data in itas well as one with data in it– We split the list into the head value and the tail to We split the list into the head value and the tail to

use for recursion so we can process the full listuse for recursion so we can process the full list

Page 25: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

List IterationList Iteration• Can be used to replace the for loop Can be used to replace the for loop

function from imperative languagesfunction from imperative languages• The map functionThe map function

– Iterates down the list by applying the specified Iterates down the list by applying the specified function to the headfunction to the head

– The tail then recurses on itself using map againThe tail then recurses on itself using map again– ExampleExample

• The filter functionThe filter function– Eliminates the values that don’t match the Eliminates the values that don’t match the

input functioninput function– Operates the same way as map except Operates the same way as map except

eliminates those without a positive bool value eliminates those without a positive bool value from the given functionfrom the given function

– ExampleExample

Page 26: Error Example - 65/4; ! Toplevel input: ! 65/4; ! ^^ ! Type clash: expression of type ! int ! cannot have type ! real

User-defined TypesUser-defined Types• Enumerated TypesEnumerated Types

– datatype Food = Burger | Chicken | Hot Dog;datatype Food = Burger | Chicken | Hot Dog;• Custom data typesCustom data typesdatatype Statsdatatype Stats

Rebounds of intRebounds of int| Point of int| Point of int| Fouls of int;| Fouls of int;– val StatsThisGame = [Rebounds 4, Point 12, Fouls 3, val StatsThisGame = [Rebounds 4, Point 12, Fouls 3,

Rebounds];Rebounds];• Can be applied over many ways and used in Can be applied over many ways and used in

functions for various purposesfunctions for various purposes