You are on page 1of 24

APLC Individual Assignment

Advanced Programming Language Concepts


(CE00331-3) INDIVIDUAL ASSIGNMENT

LIBRARY MANAGEMENT SYSTEM

Hand In Date- 5th November 2012 Hand Out Date- 30th August 2012

SUBMITTED BY: Anuja (PT0981136)

SUBMITTED TO:
Ms. Geeta Nagpal (Module Lecturer)

APIIT SD INDIA

Page i

APLC Individual Assignment

ACKNOWLEDGEMENT

First of all, I would like to express my powerful and largely under-rated thanks to my respected APLC faculty Ms. Geeta Nagpal for giving the possibility to complete this assignment with enthusiastic guidance and beneficial suggestions for improvement. Her help, support, valuable hints and encouragement motivated me a lot. I am also thankful to the library staff for providing me necessary books related to my project. I would like to thank APIIT SD INDIA, Panipat for giving me the opportunity to work in a pleasant environment and also supporting me directly or indirectly. I would also like to express our heartily gratitude to Prof. R. K. Chaudhary, Director APIIT SD INDIA for their sharing valuable time and knowledge and also for providing such facilities which had helped me to complete our assignment. At last, I am deeply indebted to express our sincere thanks to all staff members at APIIT SD INDIA, Panipat for their enthusiastic help which enabled me to complete my work.

Anuja ( PT0981136)

Ms. Geeta Nagpal (Module Lecturer)

APIIT SD INDIA

Page ii

APLC Individual Assignment

Certificate
This is to certify that Anuja (PT0981136) has submitted this Advanced Programming Language Concepts individual assignment for the partial fulfillment of seventh semester of B. E (Hons) degree course. She has successfully completed the project within specified duration, under the guidance of Ms. Geeta Nagpal (Project Supervisor) with full determination and Discipline.

SUBMITTED BY Anuja ( PT0981136)

SUBMITTED TO: Ms. Geeta Nagpal (Module Lecturer)

APIIT SD INDIA

Page iii

APLC Individual Assignment

ABSTRACT
The main objective of this module is to provide us knowledge about basics of functional and logical programming language concepts. Functional programming language being under study is Haskell where prolog as logical programming. The Haskell application is based on a Library Management System where user can check number of books available, borrowers of the book and the issue date. The application includes the use of databases and many functional programming concepts like higher order functions and recursion. The functionality of the system is divided in to five parts Find the no. of books and books name borrowed by the student Find the Borrowers of the book (Assuming more than one copy of any book) Find a book whether borrowed or not Find out the dates during which books borrowed by the student Calculate the overall fine for any student

As a librarian, user can create a new book record, create a student record, add a book, view the number of books available in library as well as calculate the fine charged to any student. In prolog application we have to create a set of Prolog rules for a given a set of basic facts and solve given queries. All the above functionalities have to use the list comprehension concept, recursion and higher order functions. Create a text based menu to handle these functionalities; recursion technique can be used in the text based menu.

APIIT SD INDIA

Page iv

APLC Individual Assignment

INTRODUCTION
Functional programming is one the oldest of major programming paradigms. Functional programming is a programming paradigm that uses the functions in their real mathematical sense. This means that functions are only computation objects where there is no mutable data and state information. This way it is more close to mathematical expressions. In contrast to imperative programming that is desperately dependent on the state of the objects, functional programming views all programs as collections of functions that accept arguments and return values. Functional programming is so called because a program consists entirely of functions. The main program itself is written as a function which receives the programs input as its argument and delivers the programs output as its result.

Haskell is a general purpose, purely functional programming language incorporating many recent innovations in programming language design. Haskell provides higher-order functions, non-strict semantics, static polymorphic typing, user-defined algebraic data types, patternmatching, list comprehensions, a module system, a monadic I/O system, and a rich set of primitive data types, including lists, arrays, arbitrary and fixed precision integers, and floating-point numbers. Haskell has adopted many of the convenient syntactic structures that have become popular in functional programming.

APIIT SD INDIA

Page v

APLC Individual Assignment Features of functional programming


Higher order function:
Haskell functions can take functions as parameters and return functions as return values. A function that does either of those is called a higher order function. Functions can take functions as parameters and also return functions. Some of those higher-order functions are map, fold, filter etc.

Map: applies the function passed to each element of the collection. Resembles to for each loops for collections in procedural languages. Filter: applies the filter function to each member of the collection and returns a list of object satisfying the conditional function. For Example: --Find whether a no is even

even1 :: Int->Bool even1 x=mod x 2==0 filt :: [Int]->[Int] filt x= filter even1 x

--Filter all even nos from a list

Recursion:
Recursion is actually a way of defining functions in which the function is applied inside its own definition. Recursion is one of the building blocks in functional programming. Since there is no other way for iteration in functional programming languages, it is the canonical and only way to implement iteration. Functional language implementations will often include tail call optimization to ensure that heavy recursion does not consume excessive memory.

Pattern matching:
Pattern matching is another powerful concept that functional and logic languages sport. It is used for assigning values to variables and for controlling the execution flow of a program. Pattern matching is used to match patterns with terms. If a pattern and term have the same shape then the match will succeed and any variables occurring in the pattern will be bound to the data structures which occur in the corresponding positions in the term.

APIIT SD INDIA

Page vi

APLC Individual Assignment


Pure functions:
In pure functional programming, side effects are not allowed in the program with immutable variable and no loops. Immutability means that when a value is assigned to an identifier (not a variable), it cannot change anymore. Loops can be achieved with recursive functions. For example following add function is pure. We calculate a result but we do not modify any existing data. var sum = add (3,4); can be replaced with var sum = 7; and there will be no change in meaning.

List Comprehension:
List comprehensions are used to derive a new list from an existing list. For example: Input: [odd x | x <- [1...9]] Output: [True, False, True, False, True, False, True, False, True]

APIIT SD INDIA

Page vii

APLC Individual Assignment


FUNCTIONAL vs. IMPERATIVE PROGRAMMING
Imperative programming is a programming paradigm that describes computation in terms of statements that change a program state. Side effects are a feature of imperative programming languages that make reasoning about the program difficult. Side effects are used to provide communication among program units. When undisciplined access to global variables is permitted, the program becomes difficult to understand.

In the imperative programming


Developer does have to take care of variables and thus think about memory locations. However in high level modern programming languages these details are hidden from the programmer. The iterative blocks and control statements makes the programs less readable and complex. The functions have Side Effects. When a function apart from returning a value makes another observable change in the system it is referred to as the Side Effect. This can happen due to shared/global state variables, IO handling, and exception. The imperative languages do not provide any mechanism to control the side effects. The use of shared state and other side effects makes the imperative languages a bad choice for parallel/concurrent programming. For concurrent execution we have to think about deadlocks/race conditions etc. in case of an imperative language.

A functional programming on the other hand


Have functions as first class citizens and every computation are treated as a function. Does not make use of variables and assignments as an imperative language. Every variable is immutable. There are no iterative blocks all repetitive tasks are done using recursion. As there is no state and mutable data functional language is said to have no side effects but in stricter terms or should say controlled side effects. functional languages maintain Referential Transparency i.e. a function whenever called using same argument returns the same result functional language is a better candidate for concurrent programming

APIIT SD INDIA

Page viii

APLC Individual Assignment


Benefits of functional programming:
The special characteristics and advantages of functional programming are often summed up more or less as follows. Functional programs contain no assignment statements, so variables, once given a value, never change. More generally, functional programs contain no side-effects at all. A function call can have no effect other than to compute its result. This eliminates a major source of bugs, and also makes the order of execution irrelevant - since no sideeffect can change the value of an expression, it can be evaluated at any time. This relieves the programmer of the burden of prescribing the flow of control. Since expressions can be evaluated at any time, one can freely replace variables by their values and vice versa - that is, programs are referentially transparent. This freedom helps make functional programs more tractable mathematically than their conventional counterparts.

APIIT SD INDIA

Page ix

APLC Individual Assignment


SCREENSHOTS: Welcome screen:
This one is the main screen or welcome screen. Here user has asked to enter the choice. User has to select one out of the given options. It will give the information about the available books and the number of books issued along with the student details such as student name .

Book Management Screen:


If user selects option 1 i.e. book management it will take him further to select between two options : search for book availability and borrowers of the book.

APIIT SD INDIA

Page x

APLC Individual Assignment


Book availability screen:
When the user searches for book availability it will give the information whether the book is available or not. If book is already borrowed it will give status as True and False if it is not.

Search book borrowers screen:


Now, if the user wants to check the borrower of a particular book he will select the second option. It will ask him name of the book and as soon as he enters the detail it will give the borrower of that particular book.

APIIT SD INDIA

Page xi

APLC Individual Assignment


Search borrowed books:
When user selects second option i.e. borrower management it provide him three options search borrowed books, search borrow date and fine calculation. After selecting first option user has asked to enter students name and output comes as total of books borrowed and list of names of the books borrowed by the particular student.

Searches borrow dates:


To search the dates of book borrowed user has asked to enter the students name and it will give the date on which the student had borrowed the book as per the format shown below.

APIIT SD INDIA

Page xii

APLC Individual Assignment


Fine calculation screen:
User can also calculate total fine for each student. Enter the student name after that user has asked to enter name of book borrowed, it will calculate the total fine one rupee for one day. The fine will be charged after one week of borrow of the book.

SOURCE CODE:
import Data.Time type Book=String type Student=String type Date=(Integer,Int,Int) type Database = [(Book,Student,Date)] bookDb::Database bookDb=[("Haskell","Anuja",(2012,10,12)),("asp.net","Deepti",(2012,10,25)),("vb.net","See ma",(2012,10 ,6)),("Project Management","Sami",(2012,8,19))] lms:: IO() lms= do

APIIT SD INDIA

Page xiii

APLC Individual Assignment

"putStrLn " @@ WELCOME TO LIBRARY MANAGEMENT SYSTEM @@@ putStrLn " Select Option ! putStrLn "Press 1 - Book Management" putStrLn "Press 2 - Borrower Management" putStrLn "Press 'q' to exit" menuopt menuopt:: IO() menuopt = do putStr "Enter your choice:" a<-getLine if a=="1" then bookmenu else if a=="2" then borrowmanage else putStrLn"Wrong Choice"

"

Code for book management


bookmenu::IO( ) bookmenu=do // function for book menu putStrLn"**********BOOK MANAGEMENT**********" putStrLn "Press- 1 Search Book availability" putStrLn "Press- 2 Search Borrowers of book" putStr "Enter your choice:" a<-getLine if a=="1" then srchbook else if a=="2" then bwbk else putStrLn"Wrong Choice" srchbook::IO() srchbook=do putStrLn"**********SEARCH BOOK STATUS**********" putStr "Enter the name of the book: " bk<-getLine putStr "Book Borrowed (True/false):" putStrLn (show(bkNum bk)) // HIGHER ORDER FUNCTION srchBr::String->[String] srchBr b=[y|(x,y,z)<-bookDb,x==b]

bkNum::String->Bool bkNum s=length (srchBr s)>0 bwbk::IO() APIIT SD INDIA Page xiv

APLC Individual Assignment


bwbk= do putStrLn"**********SEARCH BOOK BORROWERS**********" putStr "Enter the name of the book: " bk<-getLine putStr "Book Borrowers:" putStrLn (show(srchBr bk)) // HIGHER ORDER FUNCTION

Code for Borrower Management:


borrowmanage::IO( ) borrowmanage= do // function to find borrower details

putStrLn"***********BORROWER MANAGEMENT**********" putStrLn "Press- 1 Search Borrowed books & number" putStrLn "Press- 2 Search borrow dates" putStrLn "Press- 3 Calculate borrower fine" putStr "Enter your choice:" a<-getLine if a=="1" then fun1 else if a=="2" then fun2 else if a=="3" then fun3 else putStrLn"Wrong Choice" fun1::IO() fun1=do putStrLn"**********SEARCH BORROWED BOOKS & NUMBER**********" putStr "Enter the name of the student: " bk<-getLine putStr "Number of books borrowed:" putStrLn (show(length(srchBk bk))) //HIGHER ORDER FUNCTION putStr "List of books borrowed:" putStrLn (show(srchBk bk))

srchBk::String->[String] srchBk b=[x|(x,y,z)<-bookDb,y==b] brrwDt::String->[Date] brrwDt d=[z|(x,y,z)<-bookDb,y==d] fun2::IO() fun2=do putStrLn"**********SEARCH BORROW DATES**********" putStr "Enter the name of the student: " APIIT SD INDIA Page xv

APLC Individual Assignment


bk<-getLine putStr "Dates on which books borrowed:" putStrLn (show(brrwDt bk)) fun3::IO ( ) fun3=do // function putStrLn"**********CALCULATE FINE**********" putStr "Enter the name of the student: " st<-getLine putStr "Enter the name of the book: " bk<-getLine (x,y,z)<-date --putStrLn (show(head(exDate bk st))) let (a,b,c)=read(show(head(exDate bk st))) let n= read(show(diffDays (fromGregorian x y z) (fromGregorian a b c)))::Int putStr "Total fine (in INR):" putStrLn (show(fine n))

exDate::String->String->[Date] exDate a b= [z|(x,y,z)<-bookDb,y==b && x==a] date :: IO (Integer,Int,Int) -- (year,month,day) date =do a<-getCurrentTime (return . toGregorian . utctDay) a

fine::Int->Int fine n=(n-7)*1

APIIT SD INDIA

Page xvi

APLC Individual Assignment TEST PLAN


Main Module (Selection of task)
Test No 1 Expected Result User must enter correct choice i.e. not more than 2, to get the correct information. Actual Result System is asking to enter a choice according to users preference. It will give an error message for every wrong option selected. Fault Detected No fault detected Action Taken No action needed.

Find the book Module (To search the borrower)


Test No 1 Expected Result System should not allow user to enter a books name which is not available in the librarys database. Student should not be allowed to borrow a book more than once at the same time. Book quantity available in database must decrease according to student borrowing the book. Actual Result User was able to add a book which was not available in the database. System is prohibiting user to issue books more than available. Book quantity is reducing according to quantity borrowed by the student Fault Detected There was no validation for preventing user to add out of stock books. No problem detected Action Taken Required validation was applied

No action needed.

No problem detected

No action needed.

APIIT SD INDIA

Page xvii

APLC Individual Assignment


Find the borrower (To check student details)

Test No 1

Expected Result

Actual Result

Fault Detected There was no validation applied to prevent this error.

Action Taken Required action has been taken.

System should not allow Every student has two students to have given different and same student name. unique Id every time we entered student details.

Find the books borrowed (To check the book is borrowed or not)
Test No 1 Expected Result System should not allow entering wrong book details like book name. it must available in database Actual Result Fault Detected Action Taken No action needed.

Only those book No fault detected records can be seen which are available in the database.

Find the dates of books borrowed (To check the issue and return dates)
Test No 1 Expected Result Actual Result Fault Detected Action Taken No action needed.

System should not Only appropriate dates No fault detected consider wrong format of are taken into dates and it should be consideration. proper i.e. user cannot enter date above 31.

APIIT SD INDIA

Page xviii

APLC Individual Assignment


QUESTION-2 ( PROLOG) Introduction
Logic programming is a programming paradigm based on mathematical logic. In this paradigm the programmer specifies relationships among data values and use queries for execution. Prolog is the highest level general-purpose language widely used today. It is taught with a strong declarative emphasis on thinking of the logical relations between objects or entities relevant to a given problem, rather than on procedural steps necessary to solve it. The system decides the way to solve the problem, including the sequences of instructions that the computer must go through to solve it. It is easier to say what we want done and leave it to the computer to do it for us. A Prolog program is a set of procedures (the order is indifferent), each procedure consists of one or more clauses (the order of clauses is important). There are two types of clauses: facts and rules. Prolog is declarative: the program logic is expressed in terms of relations, represented as facts and rules. A computation is initiated by running a query over these relations. Clauses with bodies are called rules. A rule's body consists of calls to predicates, which are called the rules goals. Rule is of the form Head: - Body. Clauses with empty bodies are called facts. An example of a fact is: cat (tom). Assignment question-2 Create Prolog rules to find the total cost of a list of purchased items given with a set of basic facts. Facts about Cost of Items are: costofitem (cornflakes, 230). costofitem (cocacola, 210). costofitem (chocolate, 250). costofitem (crisps, 190).

APIIT SD INDIA

Page xix

APLC Individual Assignment


Source (input & output)
Q1 Fact: To find the total cost of the list of items total ([ ], 0).

Rule:

total([Item|Rest], Price) :itemcost(Item, Itemprice), total(Rest, PriceOfRest), Price is Itemprice + PriceOfRest.

Query:

Q2 Fact:

To count the list of items purchased counter ([ ],0).

Rule:

counter([Item|Rest], Total):itemcost(Item, Itemprice), counter(Rest, Tot_rest), Total is Tot_rest+1.

Query:

APIIT SD INDIA

Page xx

APLC Individual Assignment


LIMITATION & ENHANCEMENT
The system is just a prototype; there is lot of scope for future enhancements. Here are few limitations of the system.

Limitations
The software developed is menu driven; in the age of graphical user interfaces the software should at least display some higher level of graphical user interactivity. The application will be used in a building in a standalone system. It may be shared so it can be used in libraries. The system can perform only one function at a time. It is not a secure application since it has no proper authentication and authorization. Any user with physical access can use the system. The system does not implement the concept of shared and dedicated databases. For record storage the old file systems are used. During operation of system user must take care of valid input otherwise he/she has to perform all action again. For example- if at some where data type matching not done then parser will send unidentified error.

The software is incapable of transferring data. The software is not able to provide secondary storage of books and students information or history file concept; as in after you exit the program limited information from memory is stored only in file.

APIIT SD INDIA

Page xxi

APLC Individual Assignment Future Enhancement


It is an age of graphical user interfaces, now people follow just one rule which is (WYSIWYG: what you see is what you get). The software developed seeks to meet the basic requirements of assignment. Keeping in mind the boom in the banking sector, there will be lots of demand of such software but with better interface and interaction. . Therefore whenever the opportunity to redevelop the software comes the following points must be covered and included in the further development of the software. Someone has pointed Technological innovation is indeed important to economic growth and the enhancement of human possibilities. The following point developer has in mind:

Transform the software to allow some client server architecture so that interaction increases.

For this Haskell must be browser supportable. Developer has to develop any kind of plugin so that it supported over browser.

How make this functional programming interoperable like XML. Research is still on way, if this is happening in near future then system can operate over any language platform.

There is no scope to catch some major errors. So enhancement can be done in many ways. It can be upgraded to an integrated system which will include all the possible users of the system such as administrator, user etc. Proper authentication and authorization Interoperability between different stores.

Functionality of storing information on secondary medium also must be provided.

APIIT SD INDIA

Page xxii

APLC Individual Assignment CONCLUSION


A functional language has usually been considered as an academic language but I believe that this is going to change in the real feature, because functional programming has a big potential in this demanding industry. The expressiveness, powerful unique concepts such as laziness, immutability, powerful pattern matching, continuations etc. and the elegant style of programming makes the implementation of some tools easier than other paradigms. Functional languages help rapid prototyping with the aid of powerful type systems and usually with an interactive window that allows executing expressions one or more at a time. It enables to code complex algorithms without ignoring the mathematical representation. It is much easier to create domain-specific language. It improves the productivity of the developer. Tools such as static analysis tools, high-level modeling, compilation, interpretation and verification tools are one of the target areas of functional programming. This project enabled us to showcase what we learnt through out modules. It also enabled us to learn and understand functional paradigm which will surely help us in future. At last there is just one conclusion that it was a great learning experience and I thank our module lecturer to teach Haskell and Prolog.

APIIT SD INDIA

Page xxiii

APLC Individual Assignment


REFERENCES:

Haskell - HaskellWiki. 2012. Haskell - HaskellWiki. [ONLINE] Available at:http://www.haskell.org. [Accessed 02 November 2012].

Input and Output - Learn You a Haskell for Great Good! 2012 [ONLINE] Available at: http://learnyouahaskell.com/input-and-output#files-and-streams. [Accessed 30 October 2012].

Power of Functional Programming, its Features and its Future | Coding Day. 2012. [ONLINE] Available at: http://www.codingday.com/power-of-functional-

programming-its-features-and-its-future/. [Accessed 01 November 2012].

Arizona, U, 2010, Comparative Programming language, Accessed from http://www.cs.arizona.edu/~collberg/Teaching/372/2010/Handouts/Handout-15.pdf, Accessed on 1st November 2012. Kantrowitz, M, 1997, Prolog Resource Guide, Accessed from http://www.cs.cmu.edu/Groups/AI/html/faqs/lang/prolog/prg/part1/faq.html, Accessed on 4th November 2012. Bezem, M, 1997, A Prolog Compendium, Accessed from http://www.csupomona.edu/~jrfisher/www/prolog_tutorial/pt_framer.html, Accessed on 4th November 2012.

Reuben Thomas, 2000, Gentle Introduction to Haskell, version 98, [Online] Available from: http://www.haskell.org/tutorial/ [Accessed 31st October 2012]

APIIT SD INDIA

Page xxiv

You might also like