Programming in ML

Error Example
- 65/4;
! Toplevel input:
! 65/4;
! ^^
! Type clash: expression of type
! int
! cannot have type
! real
Currying Example
• Difference with left binding functions
– 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));
> val exp = fn : int -> int -> int
Type Examples
• fun cast (n:int) = n;
• fun cast n = n : int;
• fun cast n = n+”abc”;
• fun cast (n:int) = n+”abc”;
Polymorphic Functions
- fun id x = x;
> val id = fn : 'a -> 'a
- fun cond c x y = if c then x else y;
> val cond = fn : bool -> 'a -> 'a -> 'a
the Let Function
- fun prodSum x y = (x+y) * (x+y);
> val prodSum = fn : int -> int -> int
- fun prodSum x y =
let
val sumXY = x + y
in
sumXY * sumXY
end ;
> val prodSum = fn : int -> int -> int
Tuple Extraction
- let
val (u,v) = incBoth (3,5)
in
u
end;
> val it = 4 : int
The Map Function
- fun map f inpList =
case inpList of
[] => []
| (h::t) => (f h) :: (map f t)
;
> val map = fn : ('a -> 'b) -> 'a list -> 'b list
The Filter Function
- fun filter condition inpList =
case inpList of
[] => []
| (h::t) =>
if (condition h)
then h :: (filter condition t)
else filter condition t
;
> val filter = fn : ('a -> bool) -> 'a list -> 'a list
Programming in ML
By Drew Wyborski
Data Type/Operators
• Operators and types similar to C++/Java
– int, string, bool and real remain the same
– Operators have slight differences
• Additional Boolean types are included
showing the rational/logical basis
– andalso & orelse
Syntax
• Input is placed into user’s implementation
• Machine responds with result of
expression
• Specified layout for entry and output
– 3 + 4;
– val it = 7 : int
• If an error is made in entry, the machine
responds with an appropriate error
• The unit data type
Definitions
• Global constants
– val PI = 3.4;
– Help increase readability
• Functions
– fun succ n = n+1;
– val succ = fn : int  int
– Differences in calling compared to imperative
• Extensions
– if…then…else functions
– Multiple input/output functions
Currying
• An extension of function writing
• Special ability of functional language
• Left binding
• Partial evaluation (aka “currying”)
• Example
“Side-effect Free” Programming
• The interaction of functions in ML
• The use of referential-transparency occurs through the
•
•
elimination of some imperative-type features:
– Global variables
– Assignments
– Value-result parameters
– Pointers
Advantages in readability and modification in small
components or functions
Victims of elimination of side-effects
Exceptions to Referential
Transparency
• Input/Output devices
– Something outside the program is changed
– The functions have type that returns unit
• Functions because the result must be
expressed outside the interpreter
• The print function
print “Hello there \n”;
Hello there
> value it = ( ) : unit
Basic Syntactical Notes
• There is the option for expression
sequencing
• The use of sequencing leads to the loss of
previous expressions unless they have the
rare side-effect (most likely “print”)
• Comments are important as in any other
language
– Denoted through the use of (* … *)
Type Inference
• Strength of ML that helps offset loss of
imperative functions
• Ability to declare or not declare data type
– Encouraged to do so for documentation
– Similar notation to what we’ve already seen
– Allow us to make the implementer operate
correctly
– Help to clear up possible error messages
Polymorphism
• ML exhibits a strong amount of polymorphism
– Exists in function calls and data typing
– Gives us the ability to openly code for many different
data types
– Can create data variables
• Some common polymorphic functions
• Different notation associated with polymorphic
functions
Higher-Order Functions
• Used to compact functions together
• Useful to extend an already defined
function
• Helps add levels of abstraction
• Another example of the polymorphism
present in ML
Function Extension
• We are able to define some “local variables”
through the use of the let function
– This allows us to temporarily assign a value of
something to be used later in the expression
– It is only good for the part of the statement enclosed
in let expression
– Cannot use the let expression to try and mimic
imperative assignment statements
• We can also use functions in this statement
Function Extension
• There are some good guidelines that are
almost universal in writing longer
functions in ML:
– Name the function and parameters on line 1
– Indent the body of the function like you would
in Java or C++
– Include the terminating end; portion on its
own line at the end
Tuples
• Consist of pieces of data grouped together
in parenthesis
– (3,4) or (“abc”,1) or (true,”abc”,87.4)
• We can use tuples across functions just
like any other data type
• To extract individual pieces of data from
the tuple we utilize the let function
Records
• Similar to tuples except with names for
the components
• Enclosed in a set of brackets with
field=value components inside for
definition
• They are then accessed through the use
of the # function and then the field name
Lists
• Lists are created through the construction of
data values between brackets of the same type
– [1,2,3] or [“ab”,”cd”,”ef”]
• Things can be appended using ::
– 5 :: [1,2,3]  [5,1,2,3] : int list
• Concatenation is done using the @ symbol
– [1,2,3] @ [4,5,6]  [1,2,3,4,5,6] : int list
• When using functions with lists we use the case
operator
– This provides us with operations for an empty list as
well as one with data in it
– We split the list into the head value and the tail to use
for recursion so we can process the full list
List Iteration
• Can be used to replace the for loop function
•
from imperative languages
The map function
– Iterates down the list by applying the specified
function to the head
– The tail then recurses on itself using map again
– Example
• The filter function
– Eliminates the values that don’t match the input
function
– Operates the same way as map except eliminates
those without a positive bool value from the given
function
– Example
User-defined Types
• Enumerated Types
– datatype Food = Burger | Chicken | Hot Dog;
• Custom data types
datatype Stats
Rebounds of int
| Point of int
| Fouls of int;
– val StatsThisGame = [Rebounds 4, Point 12, Fouls 3, Rebounds];
• Can be applied over many ways and used in functions
for various purposes