Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Basic concepts for functional programming

 

Some of the basic concepts for learning functional programming. I noted all of them from wikipedia.

First class functions

In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens. Specifically, this means the language supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

Higher order functions

In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:

  • takes one or more functions as an input
  • outputs a function

 Map function

In many programming languages, map is the name of a higher-order function that applies a given function to each element of a list, returning a list of results. It is often called apply-to-all when considered in functional form. This is an example of functoriality.

For example, if we define a function square as follows:

square x = x * x

Then calling map square [1,2,3,4,5] will return [1,4,9,16,25], as map will go through the list and apply the function square to each element.

Filter

In functional programming, filter is a higher-order function that processes a data structure (typically a list) in some order to produce a new data structure containing exactly those elements of the original data structure for which a given predicate returns the boolean value true.

Example Scala


list.filter(pred)



Or, via for-comprehension: for(x <- list; if pred) yield x


Scope

The term "scope" is also used to refer to the set of all identifiers that are visible within a portion of the program or at a given point in a program, which is more correctly referred to as context or environment.[a]

A fundamental distinction in scoping is what "part of a program" means – whether name resolution depends on the location in the source code (lexical scope, static scope, which depends on the lexical context) or depends on the program state when the name is encountered (dynamic scope, which depends on the execution context or calling context). Lexical resolution can be determined at compile time, and is also known as early binding, while dynamic resolution can in general only be determined at run time, and thus is known as late binding.

http://en.wikipedia.org/wiki/Scope_(computer_science)

Closure

In programming languages, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment—a table storing a reference to each of the non-local variables (also called free variables or upvalues) of that function

Anonymous function

  In computer programming, an anonymous function (also function constant, function literal, or lambda function) is a function defined, and possibly called, without being bound to an identifier. Anonymous functions are convenient to pass as an argument to a higher-order function and are ubiquitous in languages with first-class functions such as Haskell. Anonymous functions are a form of nested function,

List Comprehension


A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.

Example scala

val s = for (x <- Stream.from(0) if x*x > 3) yield 2*x

parrotTrouble

Programming problem at

http://codingbat.com/prob/p140449

We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.
parrotTrouble(true, 6) → true
parrotTrouble(true, 7) → false
parrotTrouble(false, 6) → false

My Solution

First i wrote

public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;

if((talking) && ( (hour<7)||(hour>20) ) )
return true;
}

 

I got error that

Error:	public boolean parrotTrouble(boolean talking, int hour) {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This method must return a result of type boolean

Possible problem: the if-statement structure may theoretically
allow a run to reach the end of the method without calling return.
Consider using a final else {... to ensure that return is always called.

 


public boolean parrotTrouble(boolean talking, int hour) {
if(!talking)
return false;
else
return ((talking)&&( (hour<7)||(hour>20) ) );
}

The official solution was

public boolean parrotTrouble(boolean talking, int hour) {
return (talking && (hour < 7 || hour > 20));
// Need extra parenthesis around the || clause
// since && binds more tightly than ||
// && is like arithmetic *, || is like arithmetic +
}

 

Comparison and Lessons

I see that the official solution was too clean , i did extra smartness but straight away saying false if parrot is not talking. I was trying to avoid further checks. But yes official code looks good.

The main issue of missing return in first try.

We need to return always something as per function definition.

The else was missing from earlier code snippet

diff21

Programming problem at

http://codingbat.com/prob/p116624

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2
diff21(10) → 11
diff21(21) → 0

My Solution

First i wrote

public int diff21(int n) {
  int absDiff = java.Math.abs(n-21);
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

It gave error that java.Math cannot be resolved to a type. Then i realized i should not use java build in packages

Then i modified correct the code as

public int diff21(int n) {
  int absDiff = n-21;
  if (absDiff < 0 )
  absDiff = (-1)*absDiff;
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

After i read the coding rules ( see Comparison and Lessons below ) , i realized that packages are allowed to be imported

However my mistake was different , i wrote wrong java class package.

The revised correct code with build in function of abs is

public int diff21(int n) {
  int absDiff = java.lang.Math.abs(n-21);
  if(n>21)
  absDiff =  2*absDiff;
  return absDiff;
}

 

The official solution was

 

public int diff21(int n) {
if (n <= 21) {
return 21 - n;
} else {
return (n - 21) * 2;
}
}

Comparison and Lessons

I read the coding rules for CodingBat website (http://codingbat.com/help.html)  The java.util package is included in all the problems

My second mistake was to use the wrong java.lang.Math package ( i used java.Math )

Other thing which i noticed specific to CodingBat is below

If the method takes a String or array argument, those arguments will not be passed in a null. However, the empty String or array is still a valid case unless the problem statement specifically says otherwise.

Lessons learnt to remember the java Math class package

monkeyTrouble

Programming problem at

http://codingbat.com/prob/p181646

We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble.
monkeyTrouble(true, true) → true
monkeyTrouble(false, false) → true
monkeyTrouble(true, false) → false

 

My Solution

Both smiling and both not smiling , that is both true and both false points my brain towards the XOR gate

First i wrote

return (aSmile ^ bSmile );

which gave result exatly opposite to what was required , so i read the problem again

i had to change the code with

return !(aSmile ^ bSmile );

The complete solution is

 

public class monkeyTrouble {
    public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
        return !(aSmile ^ bSmile);
    }
}

 

The official solution was

 

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
if (aSmile && bSmile) {
return true;
}
if (!aSmile && !bSmile) {
return true;
}
return false;
// The above can be shortened to:
// return ((aSmile && bSmile) || (!aSmile && !bSmile));
// Or this very short version (think about how this is the same as the above)
// return (aSmile == bSmile);
}


Comparison / Analysis

Lesson learnt is to read the problem carefully and to retest your solution with dry run for possible outputs. I am going to write unit tests for testing the programs in future


I found one website which explain all the logical operators in Java


http://www.sap-img.com/java/java-boolean-logical-operators.htm

SleepIn

Programming problem at

http://codingbat.com/prob/p187868

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we're on vacation. Return true if we sleep in.
sleepIn(false, false) → true
sleepIn(true, false) → false
sleepIn(false, true) → true

 

My Solution

public class SleepIn {

    public boolean sleepIn(boolean weekday, boolean vacation) {
        if ((weekday == false) || (vacation == true))
            return true;
        else
            return false;
    }

}

 

The official solution was

 

public boolean sleepIn(boolean weekday, boolean vacation) {
if (!weekday || vacation) {
return true;
} else {
return false;
}
// This can be shortened to: return(!weekday || vacation);
}

 

Comparison

I tried to do it too childish way , comparing booleans :P

Websites for improving programming and algorithms skills

Bunch of resources for improving programming skills by practice and participating in online competitions

 

http://codingbat.com/

Online code practice which shows the right solution straight away. The best part which i like the most is that you can type your code into the text pad on website and see its output

http://livearchive.onlinejudge.org/

Here you will find hundreds of problems used in the ACM-ICPC Regional's and World Finals. You can submit your sources in a variety of languages, trying to solve any of the problems available in database.

New location is

http://uva.onlinejudge.org/index.php

 

http://www.spoj.pl/

SPOJ – Sphere Online Judge – is a problem set archive, online judge and contest hosting service accepting solutions in many languages.

http://www.topcoder.com/

This website has lots of programming contests

http://projecteuler.net/

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

http://www.codechef.com/

Participate in programming competitions , practice online questions , participate in online discussions

http://www.usaco.org/

the USA Computing Olympiad, training pages and online contests.

The USACO 2011 December contest runs from December 9 through December 12. Click Here for further details.

2011-2012 Schedule

Nov 11-14: November Contest
Dec 9-12: December Contest
Jan 6-9: January Contest
Feb 3-6: February Contest
Mar 2-5: March Contest
April: US Open
June: Training Camp
September: IOI 2012 in Milan, Italy

 

http://www.bitwise.iitkgp.ernet.in/home

IITKGP Annual Algorithms and Programming contest

Bitwise 2011 was a great success with participation from 3200 teams from over 80 countries.

Any one around the world (except students of IITKGP CSE department) can participate in the contest

 

http://www.facebook.com/careers/puzzles.php?puzzle_id=7

Puzzles for solving posted by Facebook

 

http://mathalon.in/

 

http://codercharts.com/

 

http://felicity.iiit.ac.in/

 

 

Other Resources

A website having calendar which has dates for coding contests around the world

http://home.iitk.ac.in/~pankajj/programming_calender.html

http://www.algorithmist.com/index.php/Programming_Contest_Calendar