# 编程代写 Functional Programming – cscodehelp代写

Functional Programming
The key idea:
Solving problems using functions
But, don’t all programming languages allow you to write functions?
Yes, but they provide only calls for functions and not a functional paradigm. What is the difference?
1
Functional Programming
So, what is functional programming?
• Like mathematical functions, the functions we write should depend only on their inputs and not on the program state.
• A FPL thus allow you to model computations as evaluations of functions. Similar to?
2
12
Functional vs Imperative Style
Imperative languages: Composed of step- by-step instructions for the computer (“authoratively” telling it what to do).
Functional languages: Everything is a function. In other words, a function is a first-class object that you can manipulate in its own right
3
Functional Programming
An Example:
Consider writing a program to test if a number is prime or not.
Algorithm – check to see if the number is divisible by any number between 2 and itself. If it is, it is not prime, otherwise yes. Try writing it!
4
34
Import java.util.Scanner;
Public class PrimeTest
{ public static void isPrime (int n)
{ boolean prime = true; If (n < 2) prime = false; for (int i=2; i < n; i++) { if (n%i==0) { prime = false; break; } } if (prime) What did you see? System.out.printf(“%d %s ”, n, “is a prime number”) else System.out.printf(“%d %s ”, n, “is not a prime number”) } Public static void main (String[]args) { Scanner sc = new Scanner (System.in); Sytem.out.println( “enter a number to check if its prime or not”) int num = sc.nextInt(); isPrime (num); } 5 #include ;a C program
Main() {
int n, c;
printf(“Enter a number
”); scanf(“%d”, &n);
if (n==2) printf(“Prime number.
”); else
{
for (c=2; c<=n-1; c++) { if (n%c==0) break; } if (c !=n) printf(“Not prime. ”); else printf(“Prime number. ”); } Return 0; What did you see? 6 56 1 LISP (defun is-prime (n) (isnot-divisible-between-n-2 n (- n 1))) (defun isnot-divisible-between-n-2 (n d) (or (= d 1) (and (/= (rem n d) 0) (isnot-divisible-between-n-2 n (- d 1))))) What did you see? 7 #include
Main() {
int n, c;
printf(“Enter a number
”); scanf(“%d”, &n);
if (n==2) printf(“Prime number.
”); else
{
for (c=2; c<=n-1; c++) { if (n%c==0) break; } if (c !=n) printf(“Not prime. ”); else printf(“Prime number. ”); } Return 0; Print results ?8 2 states: type integer Read & check state Manipulate states 78 9 10 #include ;a C program
Main() {
int n, c;
printf(“Enter a number
”); scanf(“%d”, &n);
Need to declare integer
if (n==2) printf(“Prime number.
”); else
{
Are these part of solving the problem?