You are on page 1of 71

LABORATORY MANUAL

Department of Computer Science and Engineering


Department of Computer Science & Engineering

LIST OF EXPERIMENTS

Expt. Title of experiment Corresponding


No. CO
1. Basic Programs in ML. C 309.1
2. Program for linear search in ML. C 3092

3. Program for binary


2. Program forsearch
binaryinsearch
ML. in ML. C 309.2

4. Program for insertion


3. Program sort in ML.
for insertion sort in ML. C 309.3
4. Program
Program forsort
for bubble bubble sort in ML.
in ML.
5. C 309.3
5. Program
Program forsort
for merge merge sort in ML.
in ML
6. C 309.3
6. Program
Program forsort
for quick quick sort in ML.
in ML. C 309.3
7.

8. Program for making


7. Program a directory
for making in ML. in ML.
a directory C 309.4
Program for merging
8. Program two unsorted
for merging list in sorted order.
two unsorted-students-name-list C 309.3
9.
in sorted order.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 2


Department of Computer Science & Engineering

Content Beyond Syllabus

10. Program to find factorial of a number in ML. C 309.1

11. Program to generate Fibonacci term in ML. C 309.1


12. Program to Create and display the sequence of binary digits C 309.1
for a given non-negative integer in ML.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 3


Department of Computer Science & Engineering

INTRODUCTION

Principles of Programming Languages is about building computational processes. We need


computational processes for computing functions, and for performing computational tasks.
The means for performing computational processes are programs. The power and weakness of
a computational process, realized within a program depends on:
1. Modeling:
− How good is the description/understanding of the computational process;
− How it is split and combined from simpler processes;
− How clear are the structures used;
− How natural is the organization of the process;
− and more.
2. Language: How powerful is the language used to write the program:
− Does it support the needed structures;
− Does it enable high level thinking, i.e., abstraction, ignoring irrelevant details;
− Does it enable modular construction;
− and more.
This subject deals with both aspects, with a greater emphasis on programming languages and
their properties. The course emphasizes the value of modularity and abstraction in modeling,
and insists on writing contracts for programs.
What is this subject about?
It is about the building, implementation and usage of programming languages in a way that
enables construction of manageable, useful and reusable products. The secret word for all this
is ABSTRACTION!
The subject introduces the following topics, in various contexts:
1. Elements of programming languages:
(a) Language building blocks: Atomic elements; composition means; abstraction.
(b) Language syntax: Concrete syntax, abstract syntax.
2. Meaning of a programming language:
(a) Operational semantics: Applicative (eager), normal (lazy); lexical scoping,
dynamic scoping.
(b) Types: Type inference, type checking; dynamic typing, static typing techniques;
polymorphic types; type specification language.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 4


Department of Computer Science & Engineering

3. Using programming languages for problem solving:


(a) Procedure abstraction: As a parameter/argument, returned value, data structure
component.
(b) Abstract data types (ADT): Abstraction – separation between application to
implementation; invariants, operation contracts, ADT embedding, Design by
Contract; hierarchical data types; lazy lists.
4. Meta-programming tools Interpreter, compiler; static (compile) time evaluation, run-time
evaluation.
5. Programming styles:
(a) Iteration vs. recursion.
(b) Continuation Passing Style.
(c) Lazy lists.
6. Software considerations and conventions: Contracts, tests, asymptotic complexity, compile
time, runtime.
7. Imperative programming: State, mutation and change in programming.

The following programming languages techniques are used:


1. Substitution operation: Used in the operational semantics algorithms and in type inference
algorithms.
2. Renaming operation: Used in the operational semantics algorithms and in type inference
algorithms.
3. Pattern matching, unification operations: Used in the operational semantics algorithms
and in type inference algorithms. 2 Introduction Principles of Programming Languages
4. Lazy/eager approaches: Used in various contexts – semantics, ADT implementation, partial
evaluation.
5. Delayed evaluation.
6. Partial evaluation: Currying.
7. Lexical scoping.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 5


Department of Computer Science & Engineering

Programming paradigms:
1. Functional programming (Scheme, Lisp, ML): Its origins are in the lambda
calculus.
2. Logic programming (Prolog): Its origins are in mathematical logic.
3. Imperative programming (ALGOL-60, Pascal, C): Its origins are in the
VonNeumann computer architecture.

For each computational paradigm we define its syntax and operational semantics and
implement a meta tool for its evaluation. We use it to solve typical problems, and study
essential properties.
Most subjects and techniques are taught using the scheme language: A small and
powerful language, designed for educational purposes.
− small – It has a very simple syntax, with few details. Can be taught in half an
hour.
− powerful – It combines, in an elegant way, the ideas of functional and
imperative programming. It can be easily used to demonstrate all programming
approaches.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 6


Department of Computer Science & Engineering

PREFACE

Functional Programming is a paradigm of programming that is most similar to evaluation of


expressions in mathematics. In functional programming a program is viewed as an expression,
which is evaluated by successive applications of functions to their arguments, and substitution
of the result for the functional expression. Its origin is in the lambda calculus of Church. The
most characteristic feature of functional programming is the lack of state during a computation.
That is, a computation is not a sequence of states, created by triggers that modify the states.
Rather, a computation is a sequence of expressions, that result from the successive evaluation of
sub-expressions. Computation in functional programming has no side-effects, because there are
no variables to be assigned. That is, the only result of a functional computation is the computed
value, and there are no additional changes that can take place during computation. Variables in
functional programming denote values, rather than locations, as in other kinds of programming
(imperative programming).

This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts
have been made to make this manual error free, yet some errors might have crept in
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 7


Department of Computer Science & Engineering

DO’S AND DONT’S

DO’s

1. Conform to the academic discipline of the department.


2. Enter your credentials in the laboratory attendance register.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out the
experiments.
5. Shut down the machine once you are done using it.

DONT’S

1. Eatables are not allowed in the laboratory.


2. Usage of mobile phones is strictly prohibited.
3. Do not open the system unit casing.
4. Do not remove anything from the computer laboratory without permission.
5. Do not touch, connect or disconnect any plug or cable without your faculty/laboratory
technician’s permission.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 8


Department of Computer Science & Engineering

GENERAL SAFETY INSTRUCTIONS

1. Know the location of the fire extinguisher and the first aid box and how to use them in
case of an emergency.

2. Report fire or accidents to your faculty /laboratory technician immediately.

3. Report any broken plugs or exposed electrical wires to your faculty/laboratory


technician immediately.

4. Do not plug in external devices without scanning them for computer viruses.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 9


as per the format given on the next two pages.

Principles of Programming Languages Lab (RCS-553) Manual (CS, V SEM) Page 10


PRINCIPLES OF PROGRAMMING LANGUAGES LAB FILE
(RCS 553)

Name

Roll No.

Section- Batch

Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 16
Department of Computer Science & Engineering

INDEX
Experiment Experiment Date of Date of Faculty
No. Name Conduction Submission Signature

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 15


Department of Computer Science & Engineering

GUIDELINES FOR ASSESSMENT

Students are provided with the details of the experiment (Aim, pre-experimental questions,
procedure etc.) to be conducted in next lab and are expected to come prepared for each lab
class.
Faculty ensures that students have completed the in-lab programming assignment(s) before
the end of class. Given that the lab programs are meant to be formative in nature, students can
ask faculty for help before and during the lab class.
Students’ performance will be assessed in each lab based on the following Lab Assessment
Components:
Assessment Criteria-1: Performance (Max. marks = 5)
Assessment Criteria-2: VIVA (Max. marks = 5)
Assessment Criteria-3: Record (Max. marks = 5)

In each lab class, students will be awarded marks out of 5 under each component head,
making it total out of 15 marks.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 16


About PPL Lab

Objective: Introduction about PPL Lab

Contents:

1. Review

o Computer Programming Language

o LISP

o PROLOG

2. Object Oriented Language

o Introduction

o Properties

3. Introduction of ML

o Definition

o Functional Programming

o Need and Application of ML

4. Data Science

Review

o Computer Programming Language

o LISP

o PROLOG

Computer Programming Language

Computer programming languages are used to communicate instructions to a computer. They are
based on certain syntactic and semantic rules, which define the meaning of each of the
programming language constructs.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 17


Interpreted Programming Languages

An interpreted language is a programming language for which most of its implementations


execute instructions directly, without previously compiling a program into machine-language
instructions. The interpreter executes the program directly, translating each statement into a
sequence of one or more subroutines already compiled into machine code.

Lisp: Lisp is the second-oldest high-level programming language in widespread use today. The
name Lisp is derived from ‘List Processing Language’. One of the important data structures that
Lisp supports is linked list. Lisp programs deal with source code as a data structure.

Pascal: It is a procedural programming language that was intended to use data structuring and
structured programming.

Perl: Perl is a high-level interpreted programming language that supports dynamic programming.

Python: It is a high-level programming language that supports imperative, object-oriented, and


functional programming paradigms. In its features like the dynamic type system and automatic
memory management, it is similar to Perl.

Ruby: The efforts for developing this language initiated in Japan in the 1990s. Similar to Perl, it
has a dynamic type system and an automatic memory management.

Functional Programming Languages

Functional programming languages define every computation as a mathematical evaluation. They


focus on the application of functions.

ML: Standard ML is popular among compiler writers and is a modular, functional programming
language. Alice is a dialect of Standard ML, which supports distributed computing, multithreading
and constraint programming. Caml is another dialect of ML and is a statically typed language that
supports automatic memory management. Ocaml is the implementation of Caml that is developed
as an open source project. JoCaml is a version of Ocaml based on join-calculus.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 18


Compiled Programming Languages

A compiled language is a programming language whose implementations are typically compilers


and not interpreters. As C, C++, C#, Fortran, Smalltalk, Visual Basic

Java: It is a general-purpose computer programming language that is concurrent, class-based,


object-oriented, and specifically designed to have as few implementation dependencies as
possible.

Procedural Programming Languages

Procedural (imperative) programming implies specifying the steps that the programs should take
to reach to an intended state. A procedure is a group of statements that can be referenced through a
procedure call.

MATLAB: It is a numerical computing environment and a programming language that enables


matrix computations, function plotting, and algorithm implementation. It can also be used for user
interface creation. MathWorks created MATLAB.

Scripting Languages: Scripting languages are programming languages that control an


application. Scripts can execute independent of any other application.

AppleScript: It is a scripting language that is built into the Mac OS.

PHP: PHP is one of the very popularly used general purpose scripting languages. It is developed
for creating dynamic web pages and supports a command line interface capability.

Markup Languages: A markup language is an artificial language that uses annotations to text
that define how the text is to be displayed.

SGML: Standardized General Markup Language (SGML)

HTML: Hypertext Markup Language, abbreviated as HTML

XML: The name stands for Extensible Markup Language.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 19


Logic-based Programming Languages

Logic programming is a type of programming paradigm which is largely based on formal logic.
Any program written in a logic programming language is a set of sentences in logical form,
expressing facts and rules about some problem domain.

Prolog: It is a general-purpose programming language that supports logic programming and is


often linked with artificial intelligence and computational linguistics. The language is declarative
and the program logic is expressed in the form of relations. Mercury is a functional logic
programming language that is based on Prolog. Strawberry Prolog is a dialect of Prolog, which is
supposed to be easy to use. Visual Prolog is a strongly typed extension of Prolog that supports
object-oriented programming. It is a compiled logic-based programming language.

Concurrent Programming Languages

Concurrent programming is a computer programming technique that provides for the execution of
operations concurrently — either within a single computer, or across a number of systems. In the
latter case, the term distributed computing is used.

ABCL: It is actually a family of Actor-Based Concurrent Languages, which was developed in


Japan during the 1980s and the 1990s.

Object-Oriented Programming Languages

Object-oriented programming (OOP) is a programming paradigm based on the concept of


“objects”, which may contain data, in the form of fields, often known as attributes; and code, in
the form of procedures, often known as methods.

Object Oriented Language

o Introduction

o Properties

Abstraction: Data abstraction refers to, providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program without
presenting the details.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 20


For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.

Encapsulation: Encapsulation is placing the data and the functions that work on that data in the
same place. While working with procedural languages, it is not always clear which functions
work on which variables but object-oriented programming provides you framework to place the
data and the relevant functions together in the same object.

Inheritance: One of the most useful aspects of object-oriented programming is code reusability.
As the name suggests Inheritance is the process of forming a new class from an existing class that
is from the existing class called as base class, new class is formed called as derived class.

This is a very important concept of object-oriented programming since this feature helps to
reduce the code size.

Polymorphism: The ability to use an operator or function in different ways in other words giving
different meaning or functions to the operators or functions is called polymorphism. Poly refers
to many. That is a single function or an operator functioning in many ways different upon the
usage is called polymorphism.

Overloading: The concept of overloading is also a branch of polymorphism. When the exiting
operator or function is made to operate on new data type, it is said to be overloaded.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 21


Introduction of ML

o Definition

o Functional Programming

o Need and Application of ML

Standard Meta Language (SML) was originally designed for theorem proving

• High quality compilers, e.g. Standard ML of New Jersey and Moscow ML, based on a
formal semantics

• SML have now may applications far away from its origins Compilers, Artificial
Intelligence, Web-applications, . . .

A Programming Language is:

1. a language for a virtual computation environment

2. a very formal language

3. precise syntax (structure)

1. Which symbols can be used, and how can they be composed

4. precise semantics (meaning)

1. What do the symbols mean

ML:

1. a functional programming language (i.e., based on math. functions)

2. designed by Robin Milner

ML Expressions -- Composition of values and operators, ended with a semicolon

1+2*3;

val it = 7 : int

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 22


ML evaluates the expression given, and prints the result

1. the result has a name - it

2. the result has a value - 7

3. the result has a type - int

Type is a very important and fundamental concept

1. defines a set of values that can be used

2. expressions must have type consistency

so, integers, reals, booleans, and strings are the fundamental types in ML

ML has Constants of five types:

1. Integers -- a string of digits (0-9), optionally preceded by a tilde (~) to indicate negative

1. Do we really need to say what an integer is? Yes.

2. Reals -- string of digits (possibly preceded by ~), followed by at least one of

1. a decimal point and one or more digits

2. the letter E, followed by an integer

3. Booleans -- true or false

4. Characters -- Ascii characters, e.g., #"A"

5. Strings -- a sequence of characters enclosed with double-quotes (")

1. \ is a special character, and means that the next character (or more) indicate
something special

2. \n is the newline character, basically just like hitting the Return key

3. \t is the tab character -- like hitting the Tab key

4. \\ is the backslash -- since one \ is special, just type \\ to really mean backslash

5. \" is the double-quote -- a plain double-quote would mean the end of the string, to
have a double-quote actually be in the string, you use \"

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 23


6. \### is a way to specify a character by its ASCII number

7. \^A for any letter A is a way to specify a control character

\ as the last character on the line means the string continues on the following line

➢ ML stands for "meta-language,"

➢ ML is a multi-paradigm, extended functional programming language. It is also often


labeled as an "impure" functional language, because it allows side-effects.

➢ ML is well known for its use of the Hindley-Milner type system that can automatically
assign the types of most expressions without explicit type annotations

➢ ML is used for a wide variety of programming:

• Scientific applications;

• Theorem provers;

• Analyzers, compilers, programming languages;

• Financial systems applications;

• Bioinformatics and genealogical databases.

➢ ML is also used in education, in introductory programming courses to demonstrate basic


programming logic and methods

➢ The ML programming language was developed in the 1970s by Robin Milner and his
colleagues at the University of Edinburgh during their work on the Logic for Computable
Functions (LCF) — an interactive automated theorem prover. LCF was implemented in
ML and introduced in 1972. ML's syntax was inspired by the ISWIM programming
language. ML is a strictly typed language.

➢ ML features an automatic memory management system through garbage collection,


where memory is automatically allocated and freed-up by the compiler. Parametric
polymorphism is supported in ML, meaning that you can write a single polymorphic
function that can take a parameter of any compatible type. ML has first class functions
and lexical closures, making it very easy to compose multiple functions, a task that can be
very complicated in imperative programming languages.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 24


➢ ML also supports polymorphic recursive data types with pattern matching, and has an
excellent module system centered on structures and signatures. ML primarily uses eager
evaluation, meaning that all sub expressions are always evaluated, while lazy evaluation
can still be achieved through the use of closures.

➢ Standard ML of New Jersey (SML/NJ) derivative and compiler, since it is the first and
most popular compiler for the ML programming language.

Data Science

Data science is a multidisciplinary blend of data inference, algorithm development, and


technology in order to solve analytically complex problems.

Data science – discovery of data insight

This aspect of data science is all about uncovering findings from data. Diving in at a granular
level to mine and understand complex behaviors, trends, and inferences. It's about surfacing
hidden insight that can help enable companies to make smarter business decisions. For example:

• Netflix data mines movie viewing patterns to understand what drives user interest, and
uses that to make decisions on which Netflix original series to produce.

• Target identifies what are major customer segments within it's base and the unique
shopping behaviors within those segments, which helps to guide messaging to different market
audiences.

• Proctor & Gamble utilizes time series models to more clearly understand future demand,
which help plan for production levels more optimally.

Data science – development of data product

A "data product" is a technical asset that:

(1) utilizes data as input, and

(2) processes that data to return algorithmically-generated results.

The classic example of a data product is a recommendation engine, which ingests user data, and
makes personalized recommendations based on that data. Here are some examples of data
products:

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 25


• Amazon's recommendation engines suggest items for you to buy, determined by their
algorithms. Netflix recommends movies to you. Spotify recommends music to you.

• Gmail's spam filter is data product – an algorithm behind the scenes processes incoming
mail and determines if a message is junk or not.

• Computer vision used for self-driving cars is also data product – machine learning
algorithms are able to recognize traffic lights, other cars on the road, pedestrians, etc.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 26


EXPERIMENT NUMBER: 1

Contents:

1. Introduction to lab (Tools , Technology, Terminology)

2. SML NJ

3. Installation Steps

4. Simple Program of ML

➢ Standard ML of New Jersey (abbreviated SML/NJ) is a compiler for the Standard ML


'97 programming language with associated libraries, tools, and documentation. SML/NJ
is free, open source software.

➢ The current release is 110.83.

➢ The current release of SML/NJ is Version 110.81, announced on August 26, 2016.
Version 110.81 runs under Linux, Mac OS X (10.6 and later), and Windows (XP an later).

Here is a summary of some of the major features of the SML/NJ system.

• The core of the SML/NJ system is an agressively optimizing compiler that produces
native machine code for most commonly used architectures: x86 (IA32), Sparc, MIPS,
IBM Power 1 (PowerPC), HPPA, and Alpha.

• SML/NJ runs under Windows 95 and NT as well as many flavors of Unix. Renewed
support for MacOS is planned for the next release.

• SML/NJ provides an interactive top level based on incremental compilation, but it can
produce stand-alone executables using the exportFn function.

• SML/NJ uses Matthias Blume's Compilation Manager, CM, to greatly simplify the
development of large software projects.

• A variety of general-purpose data structures, algorithms and utilities (such as finite sets
and maps, regular expressions, pretty-printing) are provided by the SML/NJ library.

• Concurrent programming in SML is supported by the Concurrent ML library.

• eXene is a graphical interface toolkit for X-windows based on Concurrent ML.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 27


• SML/NJ extends the SML '97 language with higher-order functors, OR-patterns, first-
class continuations, and a number of other useful features.

• Support for manipulating "object languages" (e.g. logics, calculi, simple programming
languages, specification languages) is provided by a simple quote/anitquote mechanism.

To install the SML Program, use following steps

a. Open
https://www.smlnj.org/dist/working/index.html
https://www.smlnj.org/dist/working/110.82/index.html

b. Download the smlnj latest version

c. unpack the folder (paste the folder in home)

d. open terminal write ls

e. will show folder in home

(for home no need to write cd home, by default it is in Home

f. run (in terminal at home) ------config/install.sh

g. after complete instalation

a folder in home will be created with name bin having sml

h. write cd bin

write ./sml

To run the SML Program, use following command

➢ cd Documents

➢ cd sml

➢ cd bin

➢ ./sml

Simple ML Program

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 28


1. A+B

Given two integer, A and B. Their sum needs to be calculated.

Input data: Two integers are written in the input stream, separated by space(s):

Output data: The required output is one integer: the sum of A and B.

Example

input output

22 4

32 5

(*
* val split : string -> string list
* splits a string at it spaces
*)
val split = String.fields (fn #" " => true | _ => false)

(*
* val removeNl : string -> string
* removes the occurence of "\n" in a string
*)
val removeNl = String.translate (fn #"\n" => "" | c => implode [c])

(*
* val aplusb : unit -> int
* reads a line and gets the sum of the numbers
*)
fun aplusb () =
let
val input = removeNl (valOf (TextIO.inputLine TextIO.stdIn))
in
foldl op+ 0 (map (fn s => valOf (Int.fromString s)) (split input))
end

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 29


Output:

- aplusb();

123 456

val it = 579 : int

2. Arithmetic/Integer

Get two integers from the user, and then (for those two integers), display their:

• Sum, difference, product, integer quotient, remainder, exponentiation (if the operator exists)

val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
in
print ("a + b = " ^ Int.toString (a + b) ^ "\n");
print ("a - b = " ^ Int.toString (a - b) ^ "\n");
print ("a * b = " ^ Int.toString (a * b) ^ "\n");
print ("a div b = " ^ Int.toString (a div b) ^ "\n"); (* truncates towards negative infinity *)
print ("a mod b = " ^ Int.toString (a mod b) ^ "\n"); (* same sign as second operand *)
print ("a quot b = " ^ Int.toString (Int.quot (a, b)) ^ "\n");(* truncates towards 0 *)
print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n"); (* same sign as first operand *)
print ("~a = " ^ Int.toString (~a) ^ "\n") (* unary negation, unusual notation
compared to other languages *)
end

3. Array length

Determine the amount of elements in an array.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 30


As an example use an array holding the strings 'apple' and 'orange'.

let
val a = Array.fromList ["apple", "orange"]
in
Array.length a
end;

4. Combinations

Given non-negative integers m and n, generate all size m combinations of the integers
from 0 (zero) to n-1 in sorted order (each combination is sorted and the entire table is
sorted).

Example

3 comb 5 is:

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 31


012

013

014

023

024

034

123

124

134

234

If it is more "natural" in your language to start counting from 1 (unity) instead of 0


(zero),
the combinations can be of the integers from 1 to n.

fun comb (0, _ ) = [[]]


| comb (_, [] ) = []
| comb (m, x::xs) = map (fn y => x :: y) (comb (m-1, xs)) @
comb (m, xs)
;
comb (3, [0,1,2,3,4]);

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 32


5. Date format

Display the current date in the formats of:

• 2007-11-23 and

• Sunday, November 23, 2007

• print (Date.fmt "%Y-%m-%d" (Date.fromTimeLocal (Time.now ())) ^ "\n");


print (Date.fmt "%A, %B %d, %Y" (Date.fromTimeLocal (Time.now ())) ^ "\n");

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 33


6. Greatest element of a list

Create a function that returns the maximum value in a provided set of values,
where the number of values may not be known until run-time.

Comparisons are specific for each type. Here is a max function for a list of ints:

fun max_of_ints [] = raise Empty


| max_of_ints (x::xs) = foldl Int.max x xs

- max_of_ints [4,3,5,9,2,3];

val it = 9 : int

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 34


7. Hello world/Newline omission

Display the string Goodbye, World! without a trailing newline.

print "Goodbye, World!"

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 35


8. Increment a numerical string

Int.toString (1 + valOf (Int.fromString "1234"))

9. Loops/While

Start an integer value at 1024.

Loop while it is greater than zero.

Print the value (with a newline) and divide it by two each time through the loop.

val n = ref 1024;


while !n > 0 do (
print (Int.toString (!n) ^ "\n");
n := !n div 2
)

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 36


But it is more common to write it in a tail-recursive functional style:

let
fun loop n =
if n > 0 then (
print (Int.toString n ^ "\n");
loop (n div 2)
) else ()
in
loop 1024
end

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 37


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 38
EXPERIMENT NUMBER: 2

Objective: Program for linear search in ML

Contents:

Searching techniques

Searching is an operation or a technique that helps finds the place of a given element or value in
the list. Any search is said to be successful or unsuccessful depending upon whether the element
that is being searched is found or not. Some of the standard searching technique that is being
followed in the data structure is listed below:

• Linear Search or Sequential Search

• Binary Search

Linear search

Basics

Need and Linear Search

This is the simplest method for searching. In this technique of searching, the element to be found
in searching the elements to be found is searched sequentially in the list. This method can be
performed on a sorted or an unsorted list (usually arrays). In case of a sorted list searching starts
from 0th element and continues until the element is found from the list or the element whose
value is greater than (assuming the list is sorted in ascending order), the value being searched is
reached.

fun find_index (pred, lst) = let


fun loop (n, []) = NONE
| loop (n, x::xs) = if pred x then SOME n
else loop (n+1, xs)
in
loop (0, lst)
end;

val haystack = ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"];

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 39


app (fn needle =>
case find_index (fn x => x = needle, haystack) of
SOME i => print (Int.toString i ^ " " ^ needle ^ "\n")
| NONE => print (needle ^ " is not in haystack\n"))
["Washington", "Bush"];

Search a list of records

Many programming languages provide convenient ways to look for a known value in a simple
list of strings or numbers.

But what if the elements of the list are themselves compound records/objects/data-structures, and
the search condition is more complex than a simple equality test?

Task: Write a function/method/etc. that can find the first element in a given list matching a given
condition.
It should be as generic and reusable as possible.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 40


(Of course if your programming language already provides such a feature, you can use that instead of
recreating it.)

Then to demonstrate its functionality, create the data structure specified under #Data set, and
perform on it the searches specified under

Data set

The data structure to be used contains the names and populations (in millions) of the 10 largest
metropolitan areas in Africa, and looks as follows when represented in JSON:

[
{ "name": "Lagos", "population": 21.0 },
{ "name": "Cairo", "population": 15.2 },
{ "name": "Kinshasa-Brazzaville", "population": 11.3 },
{ "name": "Greater Johannesburg", "population": 7.55 },
{ "name": "Mogadishu", "population": 5.85 },
{ "name": "Khartoum-Omdurman", "population": 4.98 },
{ "name": "Dar Es Salaam", "population": 4.7 },
{ "name": "Alexandria", "population": 4.58 },
{ "name": "Abidjan", "population": 4.4 },
{ "name": "Casablanca", "population": 3.98 }
]

However, you shouldn't parse it from JSON, but rather represent it natively in your programming
language.

• The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar).

• Each element in this list should be an associative collection that maps from keys to values (i.e. a
struct, object, hash map, dictionary, or similar).

• Each of them has two entries: One string value with key "name", and one numeric value with key
"population".

• You may rely on the list being sorted by population count, as long as you explain this to readers.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 41


If any of that is impossible or unreasonable in your programming language, then feel free to
deviate, as long as you explain your reasons in a comment above your solution.

Test cases

Search Expected result

Find the (zero-based) index of the first city in the list whose name is "Dar Es
6
Salaam"

Find the name of the first city in this list whose population is less than 5 Khartoum-
million Omdurman

Find the population of the first city in this list whose name starts with the
4.58
letter "A"

Guidance

If your programming language supports higher-order programming, then the most elegant way to
implement the requested functionality in a generic and reusable way, might be to write a function
(maybe called "find_index" or similar), that takes two arguments:

1. The list to search through.

2. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each


element in the list, and whose boolean return value defines whether that element matches the search
requirement.

If this is not the approach which would be most natural or idiomatic in your language, explain
why, and show what is.

type city = { name : string, population : real }

val citys : city list = [


{ name = "Lagos", population = 21.0 },
{ name = "Cairo", population = 15.2 },

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 42


{ name = "Kinshasa-Brazzaville", population = 11.3 },
{ name = "Greater Johannesburg", population = 7.55 },

{ name = "Mogadishu", population = 5.85 },


{ name = "Khartoum-Omdurman", population = 4.98 },
{ name = "Dar Es Salaam", population = 4.7 },
{ name = "Alexandria", population = 4.58 },
{ name = "Abidjan", population = 4.4 },
{ name = "Casablanca", population = 3.98 } ]

val firstCityi = #1 (valOf (List.findi (fn (_, city) => #name(city) = "Dar Es Salaam") citys))
val firstBelow5M = #name (valOf (List.find (fn city => #population(city) < 5.0) citys))
val firstPopA = #population (valOf (List.find (fn city => String.substring (#name(city), 0, 1) =
"A") citys))

Output:

val firstCityi = 6 : int

val firstBelow5M = "Khartoum-Omdurman" : string

val firstPopA = 4.58 : real

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 43


Linear Search Program in ML

use "/home/sak/sml/programs/random.sml";

local

(* INV: 0<=i<= l = len(L) /\ forall j: 0<=j<i: a =/= L[j] *)

fun linsearch (a, [], i) = i

| linsearch (a, h::T, i) = if a=h then i else linsearch (a, T, i+1)

in fun search (a, L) =

let val l = length L


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 44
val i = linsearch (a, L, 0)

in if i >= l then print ("not found\n")

else print ("found at index "^Int.toString(i)^"\n")

end

end

val A = mkIntRandlist 1000;

val a = randomInt ();

search (a, A);

val b = List.nth (A, 786);

search (b, A)

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 45


EXPERIMENT NUMBER: 3

Objective: Program for binary search in ML

Contents:

1. Binary search

o Basics

o Need and Binary Search

o Binary Search Program in ML

o Compare Binary Search vs. Linear Search technique

Basics

Binary search is a very fast and efficient searching technique. It requires the list to be in sorted order. In
this method, to search an element you can compare it with the present element at the center of the list. If it
matches, then the search is successful otherwise the list is divided into two halves: one from the 0 thelement
to the middle element which is the center element (first half) another from the center element to the last
element (which is the 2nd half) where all values are greater than the center element.

Need and Binary Search

Binary Search Program in ML

Compare Binary Search vs. Linear Search technique

A linear search scans one item at a time, without jumping to any item .

1. The worst case complexity is O(n), sometimes known an O(n) search

2. Time taken to search elements keep increasing as the number of elements are increased.

A binary search however, cut down your search to half as soon as you find middle of a sorted list.

1. The middle element is looked to check if it is greater than or less than the value to be searched.

2. Accordingly, search is done to either half of the given list

Department of Computer Science & Engineering

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 46


Important Differences

▪ Input data needs to be sorted in Binary Search and not in Linear Search

▪ Linear search does the sequential access whereas Binary search access data randomly.

▪ Time complexity of linear search -O(n) , Binary search has time complexity O(log n).

▪ Linear search performs equality comparisons and Binary search performs ordering comparisons

Linear Search to find the element “J” in a given sorted list from A-X

Binary Search to find the element “J” in a given sorted list from A-X

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 47


Binary search is much faster than linear search. Binary Search requires O(log N) steps where N is the
size of the search space. But linear search needsO(N) steps in the worst case, but doesn't require the data
to be sorted, or the function to be monotonous. ... In searching arrays, it should be sorted.

A binary search divides a range of values into halves, and continues to narrow down the field of
search until the unknown value is found. It is the classic example of a "divide and conquer"
algorithm.

As an analogy, consider the children's game "guess a number." The scorer has a secret number,
and will only tell the player if their guessed number is higher than, lower than, or equal to the
secret number. The player then uses this information to guess a new number.

As the player, an optimal strategy for the general case is to start by choosing the range's midpoint
as the guess, and then asking whether the guess was higher, lower, or equal to the secret number.
If the guess was too high, one would select the point exactly between the range midpoint and the
beginning of the range. If the original guess was too low, one would ask about the point exactly
between the range midpoint and the end of the range. This process repeats until one has reached
the secret number.

Task: Given the starting point of a range, the ending point of a range, and the "secret value", implement a
binary search through a sorted integer array for a certain number. Implementations can be recursive or
iterative (both if you can). Print out whether or not the number was in the array afterwards. If it was, print
the index also.

There are several binary search algorithms commonly seen. They differ by how they treat
multiple values equal to the given value, and whether they indicate whether the element was
found or not. For completeness we will present pseudocode for all of them.

All of the following code examples use an "inclusive" upper bound (i.e. high = N-1 initially).
Any of the examples can be converted into an equivalent example using "exclusive" upper
bound (i.e. high = N initially) by making the following simple changes (which simply
increase high by 1):

• change high = N-1 to high = N

• change high = mid-1 to high = mid

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 48


• (for recursive algorithm) change if (high < low) to if (high <= low)

• (for iterative algorithm) change while (low <= high) to while (low < high)

Recursive

fun binary_search cmp (key, arr) =


let
fun aux slice =
if ArraySlice.isEmpty slice then
NONE
else
let
val mid = ArraySlice.length slice div 2
in
case cmp (ArraySlice.sub (slice, mid), key)
of LESS => aux (ArraySlice.subslice (slice, mid+1, NONE))
| GREATER => aux (ArraySlice.subslice (slice, 0, SOME mid))
| EQUAL => SOME (#2 (ArraySlice.base slice) + mid)
end
in
aux (ArraySlice.full arr)
end;

Usage:

- val a = Array.fromList [2, 3, 5, 6, 8];

val a = [|2,3,5,6,8|] : int array

- binary_search Int.compare (4, a);

val it = NONE : int option

- binary_search Int.compare (8, a);

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 49


val it = SOME 4 : int option

Standard ML supports proper tail-recursion; so this is effectively the same as iteration.

Works with: SML/NJ

Usage:

- structure IntArray = struct

= open Array

= type elem = int

= type array = int Array.array

= type vector = int Vector.vector

= end;

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 50


structure IntArray :

sig

[ ... rest omitted ]

- structure IntBSearch = BSearchFn (IntArray);

structure IntBSearch :

sig

structure A : <sig>

val bsearch : ('a * A.elem -> order)

-> 'a * A.array -> (int * A.elem) option

end

- val a = Array.fromList [2, 3, 5, 6, 8];

val a = [|2,3,5,6,8|] : int array

- IntBSearch.bsearch Int.compare (4, a);

val it = NONE : (int * IntArray.elem) option

- IntBSearch.bsearch Int.compare (8, a);

val it = SOME (4,8) : (int * IntArray.elem) option

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 51


EXPERIMENT NUMBER: 4

Objective: Program for insertion sort in ML

Contents:

1. Sorting

a. Basics

b. Need of Sorting

c. Sorting Technique

2. Insertion sort

a. Basics

b. Need Insertion Sort

c. Insertion sort in ML

An O(n2) sorting algorithm which moves elements one at a time into the correct position. The
algorithm consists of inserting one element at a time into the previously sorted part of the array,
moving higher ranked elements up as necessary. To start off, the first (or smallest, or any
arbitrary) element of the unsorted array is considered to be the sorted part.

Although insertion sort is an O(n2) algorithm, its simplicity, low overhead, good locality of
reference and efficiency make it a good choice in two cases:

(i) small n,

(ii) as the final finishing-off algorithm for O(n logn) algorithms such
as mergesort and quicksort.

The algorithm is as follows:

function insertionSort(array A)

for i from 1 to length[A]-1 do

value := A[i]

j := i-1

while j >= 0 and A[j] > value do


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 52
A[j+1] := A[j]

j := j-1

done

A[j+1] = value

done

Program

fun insertion_sort cmp = let


fun insert (x, []) = [x]
| insert (x, y::ys) =
case cmp (x, y) of GREATER => y :: insert (x, ys)
|_ => x :: y :: ys
in
foldl insert []
end;

insertion_sort Int.compare [6,8,5,9,3,2,1,4,7];

EXPERIMENT NUMBER: 5
Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 53
Objective: Program for bubble sort in ML

Contents:

1. Bubble sort

o Basics

o Need Bubble Sort

o Bubble sort in ML

o Compare Insertion Sort vs. Bubble Sort technique

Sort an array of elements using the bubble sort algorithm. The elements must have a total order
and the index of the array can be of any discrete type. For languages where this is not possible,
sort an array of integers.

The bubble sort is generally considered to be the simplest sorting algorithm.

Because of its simplicity and ease of visualization, it is often taught in introductory computer
science courses.

Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized)
datasets.

The bubble sort works by passing sequentially over a list, comparing each value to the one
immediately after it. If the first value is greater than the second, their positions are switched.
Over a number of passes, at most equal to the number of elements in the list, all of the values
drift into their correct positions (large values "bubble" rapidly toward the end, pushing others
down around them). Because each pass finds the maximum item and puts it at the end, the
portion of the list to be sorted can be reduced at each pass. A boolean variable is used to track
whether any changes have been made in the current pass; when a pass completes without
changing anything, the algorithm exits.

This can be expressed in pseudo-code as follows (assuming 1-based indexing):

repeat

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 54


hasChanged := false

decrement itemCount

repeat with index from 1 to itemCount

if (item at index) > (item at (index + 1))

swap (item at index) with (item at (index + 1))

hasChanged := true

until hasChanged = false

Program

fun bubble_select [] = []

| bubble_select [a] = [a]

| bubble_select (a::b::xs) =

if b < a then b::(bubble_select(a::xs)) else a::(bubble_select(b::xs))

fun bubblesort [] = []

| bubblesort (x::xs) =bubble_select (x::(bubblesort xs))

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 55


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 56
EXPERIMENT NUMBER: 6

Objective: Program for merge sort in ML

Contents:

1. Merge sort

o Basics

o Need Merge Sort

o Merge sort in ML

o Compare Insertion Sort, Bubble Sort and Merge Sorting technique

The merge sort is a recursive sort of order n*log(n).

It is notable for having a worst case and average complexity of O(n*log(n)), and a best case
complexity of O(n) (for pre-sorted input).

The basic idea is to split the collection into smaller groups by halving it until the groups only
have one element or no elements (which are both entirely sorted groups).

Then merge the groups back together so that their elements are in order.

This is how the algorithm gets its divide and conquer description.

Task: Write a function to sort a collection of integers using the merge sort.

The merge sort algorithm comes in two parts:

a sort function and

a merge function

The functions in pseudocode look like this:

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 57


function mergesort(m)

var list left, right, result

if length(m) ≤ 1

return m

else

var middle = length(m) / 2

for each x in m up to middle - 1

add x to left

for each x in m at and after middle

add x to right

left = mergesort(left)

right = mergesort(right)

if last(left) ≤ first(right)

append right to left

return left

result = merge(left, right)

return result

function merge(left,right)

var list result

while length(left) > 0 and length(right) > 0

if first(left) ≤ first(right)

append first(left) to result

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 58


left = rest(left)

else

append first(right) to result

right = rest(right)

if length(left) > 0

append rest(left) to result

if length(right) > 0

append rest(right) to result

return result

Program

fun merge cmp ([], ys) = ys


| merge cmp (xs, []) = xs
| merge cmp (xs as x::xs', ys as y::ys') =
case cmp (x, y) of GREATER => y :: merge cmp (xs, ys')
|_ => x :: merge cmp (xs', ys)
;
fun merge_sort cmp [] = []
| merge_sort cmp [x] = [x]
| merge_sort cmp xs = let
val ys = List.take (xs, length xs div 2)
val zs = List.drop (xs, length xs div 2)
in
merge cmp (merge_sort cmp ys, merge_sort cmp zs)
end
;
merge_sort Int.compare [8,6,4,2,1,3,5,7,9]

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 59


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 60
EXPERIMENT NUMBER: 7

Objective: Program for Quick sort in ML

Contents:

Quick sort

o Basics

o Need Quick Sort

o Quick sort in ML

o Compare Insertion Sort, Bubble Sort, Merge sort and Quick Sorting technique

Sort an array (or list) elements using the quicksort algorithm.

The elements must have a strict weak order and the index of the array can be of any discrete
type.

For languages where this is not possible, sort an array of integers.

Quicksort, also known as partition-exchange sort, uses these steps.

1. Choose any element of the array to be the pivot.

2. Divide all other elements (except the pivot) into two partitions.

• All elements less than the pivot must be in the first partition.

• All elements greater than the pivot must be in the second partition.

3. Use recursion to sort both partitions.

4. Join the first sorted partition, the pivot, and the second sorted partition.

The best pivot creates partitions of equal length (or lengths differing by 1).

The worst pivot creates an empty partition (for example, if the pivot is the first or last
element of a sorted array).

The run-time of Quicksort ranges from O(n log n) with the best pivots, to O(n2) with the
worst pivots, where n is the number of elements in the array.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 61


This is a simple quicksort algorithm, adapted from Wikipedia.

function quicksort(array)

less, equal, greater := three empty arrays

if length(array) > 1

pivot := select any element of array

for each x in array

if x < pivot then add x to less

if x = pivot then add x to equal

if x > pivot then add x to greater

quicksort(less)

quicksort(greater)

array := concatenate(less, equal, greater)

A better quicksort algorithm works in place, by swapping elements within the array, to avoid
the memory allocation of more arrays.

Program

fun quicksort [] = []
| quicksort (x::xs) =
let
val (left, right) = List.partition (fn y => y<x) xs
in
quicksort left @ [x] @ quicksort right
end

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 62


Without using List.partition

fun par_helper([], x, l, r) = (l, r) |


par_helper(h::t, x, l, r) =
if h <= x then
par_helper(t, x, l @ [h], r)
else
par_helper(t, x, l, r @ [h]);

fun par(l, x) = par_helper(l, x, [], []);

fun quicksort [] = []
| quicksort (h::t) =
let
val (left, right) = par(t, h)
in
quicksort left @ [h] @ quicksort right
end;

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 63


EXPERIMENT NUMBER: 8

Objective: Program for making a dictionary in ML

Contents:

A dictionary (or map) in computer science is a data structure that maps keys to values such that given a key its
corresponding value can be efficiently retrieved.

Program

structure Dictionary :> DICTIONARY =

struct

datatype (''key, 'value) dict = Dict of (''key * 'value) list

exception NotFound

fun create () = Dict [];

fun exists (Dict ls) name =

List.exists (fn (n, v) => (n = name)) ls

fun lookup (Dict ((n, v) :: others)) name =

if n = name

then v

else lookup (Dict others) name

| lookup (Dict []) name = raise NotFound;

fun size (Dict ls) = List.length ls;

fun isEmpty (Dict []) = true

| isEmpty _ = false;

fun update (Dict ts) name value =

let

fun inup checked ((n, v) :: others) =

if n = name then

(n, value) :: (checked @ others)

else

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 64


inup ((n, v) :: checked) others

| inup checked [] = (name, value) :: checked

in

Dict (inup [] ts)

end;

fun remove (Dict ts) name =

let

fun rm checked ((n, v) :: others) =

if n = name

then rm checked others

else rm ((n, v) :: checked) others

| rm checked [] = checked

in

Dict (rm [] ts)

end

fun aslist (Dict ls) = ls;

fun keys (Dict ((n, _) :: others)) = n :: (keys (Dict others))

| keys (Dict []) = [];

fun items (Dict ((_, v) :: others)) = v::(items (Dict others))

| items (Dict []) = [];

fun mapkeys (Dict ls) f =

Dict (map (fn (k, v) => (f k, v)) ls);

fun mapitems (Dict ls) f =

Dict (map (fn (k, v) => (k, f v)) ls);

end;

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 65


EXPERIMENT NUMBER: 9

Objective: Program for merging two unsorted list in sorted order

Contents:

Take two lists, each of which is unsorted, and merges the two together into one new
list which is in sorted (increasing) order, should return the new list.
We first sort both the given list separately. Then we simply merge two sorted list.

Program

fun member (element, nil) = false

| member (element, set) = if element = hd set then true

else member (element, tl set);

fun merge (nil, nil) = nil

| merge (nil, L) = L

| merge (L, nil) = L

| merge (L1, L2) =

if (hd L1) > (hd L2)

then (hd L2)::(hd L1)::merge(tl L1, tl L2)

else (hd L1)::(hd L2)::merge(tl L1, tl L2);

val odd = [1,3,5,7,9,11,13,15,17,19,21];

val even = [2,4,6,8,10,12,14,16,18,20];

merge (odd, even);

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 66


EXPERIMENT NUMBER: 10

Objective: Program to find factorial of a number in ML.

Contents:

The factorial of 0 (zero) is defined as being 1 (unity).

The Factorial Function of a positive integer, n, is defined as the product of the sequence:

n, n-1, n-2, ... 1

Program:

fun factorial n =
if n <= 0 then 1
else n * factorial (n-1)

The following is tail-recursive, so it is effectively iterative:

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 67


fun factorial n = let
fun loop (i, accum) =
if i > n then accum
else loop (i + 1, accum * i)
in
loop (1, 1)
end

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 68


EXPERIMENT NUMBER: 11

Objective: Program to generate Fibonacci term in ML.

Contents:

The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:

F0 = 0

F1 = 1

Fn = Fn-1 + Fn-2, if n>1

Solutions can be iterative or recursive (though recursive solutions are generally considered too
slow and are mostly used as an exercise in recursion).

The sequence is sometimes extended into negative numbers by using a straightforward inverse of
the positive definition:

Fn = Fn+2 - Fn+1, if n<0

support for negative n in the solution is optional.

Program:

This version is tail recursive.

fun fib n =
let
fun fib' (0,a,b) = a
| fib' (n,a,b) = fib' (n-1,a+b,a)
in
fib' (n,0,1)
end

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 69


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 70
EXPERIMENT NUMBER: 12

Objective: Program to Create and display the sequence of binary digits for a given non-
negative integer in ML.

Contents:

The decimal value 5 should produce an output of 101

The decimal value 50 should produce an output of 110010

The decimal value 9000 should produce an output of 10001100101000

The results can be achieved using built-in radix functions within the language (if these are
available), or alternatively a user defined function can be used.

The output produced should consist just of the binary digits of each number followed by a
newline.

There should be no other whitespace, radix or sign markers in the produced output, and leading
zeros should not appear in the results.

Program:

print (Int.fmt StringCvt.BIN 5 ^ "\n");


print (Int.fmt StringCvt.BIN 50 ^ "\n");
print (Int.fmt StringCvt.BIN 9000 ^ "\n");

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 71


Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 72
Department of Computer Science & Engineering

References

1. Greg Michaelson , “A Practical Course in Functional Programming Using Standard ML” ,


UCL press.

2. Richard Bosworth, “A Practical Course in Functional Programming Using Standard ML”,


McGraw-Hill.

3. Rachel Harrison, “Abstract Data Types in Standard ML”, John Wiley & Sons.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 73


Department of Computer Science & Engineering

APPENDIX

AKTU SYLLABUS

RCS 553: PRINCIPLES OF PROGRAMMING LANGUAGES LAB

1. Program for linear search in ML.

2. Program for binary search in ML.

3. Program for insertion sort in ML.

4. Program for bubble sort in ML.

5. Program for merge sort in ML.

6. Program for quick sort in ML.

7. Program for making a directory in ML.

8. Program for merging two unsorted list in sorted order.

Principles of Programming languages Lab (RCS-553) Manual (CS, V SEM) Page 74

You might also like