From b54d5336f2202100e52e52c262a5c0dad823413f Mon Sep 17 00:00:00 2001 From: Arkadiusz Hypki Date: Mon, 20 May 2024 13:36:41 +0200 Subject: [PATCH] 'Added Java functional programming tutorial and excercises;' --- 07_OpenMP/ex1/src/openmp1.c | 90 +++++++++--------- 09_JavaFP/ex.txt | 10 ++ .../javafp/ArraysFunctionalProgramming.java | 55 +++++++++++ .../hypki/wmi/javafp/FunctionChaining.java | 39 ++++++++ .../wmi/javafp/ImperativeVsDeclarative.java | 70 ++++++++++++++ .../src/net/hypki/wmi/javafp/Parallel.java | 94 +++++++++++++++++++ .../javafp/RunnableFunctionalProgramming.java | 33 +++++++ 7 files changed, 345 insertions(+), 46 deletions(-) create mode 100644 09_JavaFP/ex.txt create mode 100644 09_JavaFP/src/net/hypki/wmi/javafp/ArraysFunctionalProgramming.java create mode 100644 09_JavaFP/src/net/hypki/wmi/javafp/FunctionChaining.java create mode 100644 09_JavaFP/src/net/hypki/wmi/javafp/ImperativeVsDeclarative.java create mode 100644 09_JavaFP/src/net/hypki/wmi/javafp/Parallel.java create mode 100644 09_JavaFP/src/net/hypki/wmi/javafp/RunnableFunctionalProgramming.java diff --git a/07_OpenMP/ex1/src/openmp1.c b/07_OpenMP/ex1/src/openmp1.c index d666269..5810692 100644 --- a/07_OpenMP/ex1/src/openmp1.c +++ b/07_OpenMP/ex1/src/openmp1.c @@ -1,59 +1,57 @@ -/* - ============================================================================ - Name : openmp1.c - Author : - Version : - Copyright : Your copyright notice - Description : Hello World in C, Ansi-style - ============================================================================ - */ - #include #include #include +#include +void maks(int numThreads, int my_array[]) +{ + int globMaks = 0; + int threadMaks = 0; + int a = 10; + clock_t start = clock(); + omp_set_num_threads(numThreads); + #pragma omp parallel private(threadMaks) shared(globMaks) + { + #pragma omp for + for (int i = 0; i < a; i++) + { + if (my_array[i] > threadMaks) + { + threadMaks = my_array[i]; + } + } -void sum() { - int partial_Sum, total_Sum; - - #pragma omp parallel private(partial_Sum) shared(total_Sum) - { - partial_Sum = 0; - total_Sum = 0; - - #pragma omp for - for(int i = 1; i <= 10; i++) { - partial_Sum += i; - } - - //Create thread safe region. - #pragma omp critical - { - //add each threads partial sum to the total sum - total_Sum += partial_Sum; - } - } - printf("Total Sum: %d\n", total_Sum); + #pragma omp critical + { + if (threadMaks > globMaks) + { + globMaks = threadMaks; + } + } + } + clock_t end = clock(); + float seconds = (float)(end - start) / CLOCKS_PER_SEC; + printf("\n%d maksymalna dla %d watkow, czas: %f \n", globMaks, numThreads, seconds); + printf("\n"); } + int main(void) { - puts("!!!Hello World!!!"); /* prints !!!Hello World!!! */ + const int a = 10; + int my_array[a]; + srand(time(NULL)); + for (int i = 0; i < a; i++) { + my_array[i] = rand(); + } - const int numThreads = 4; - int a[numThreads]; - omp_set_num_threads(numThreads); - #pragma omp parallel - { - int id = omp_get_thread_num(); - a[id] = id + 1; - } + for (int i = 0; i < a; i++) { + printf("%d ", my_array[i]); + } - for (int i = 0; i < numThreads; i++) { - printf("Hello from thread %d\n", a[i]); - } + int globMaks; + int threadMaks = 0; - sum(); -// sum2(); + maks(2, my_array); - return EXIT_SUCCESS; + return EXIT_SUCCESS; } diff --git a/09_JavaFP/ex.txt b/09_JavaFP/ex.txt new file mode 100644 index 0000000..1cf0c67 --- /dev/null +++ b/09_JavaFP/ex.txt @@ -0,0 +1,10 @@ +1. Write Lambda expression in Java which implements sum of two integers + +2. Write Lambda expression in Java which removes duplicates from a list + +3. Write Lambda expression in Java which capitalize all strings + +4. Write Lambda expression in Java which finds all even and odd numbers + +5. Write Lambda expression in Java which finds the average length of strings in a list. + diff --git a/09_JavaFP/src/net/hypki/wmi/javafp/ArraysFunctionalProgramming.java b/09_JavaFP/src/net/hypki/wmi/javafp/ArraysFunctionalProgramming.java new file mode 100644 index 0000000..b550386 --- /dev/null +++ b/09_JavaFP/src/net/hypki/wmi/javafp/ArraysFunctionalProgramming.java @@ -0,0 +1,55 @@ +package net.hypki.wmi.javafp; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; + +public class ArraysFunctionalProgramming { + + // Java program to demonstrate an + // external iterator + public static void printArrayWithIterator() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + // External iterator, for Each loop + for (Integer n : numbers) { + System.out.print(n + " "); + } + System.out.println(); + } + + public static void printArrayWithIndices() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + // External iterator, with indices + for (int i = 0; i < numbers.size(); i++) { + System.out.print(numbers.get(i) + " "); + } + System.out.println(); + } + + public static void printArrayWithLambdas() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + // Internal iterator + numbers.forEach(number -> System.out.print(number + " ")); + System.out.println(); + + // it is the same as implementing interfaces, but with interfaces it is a little bit more ugly + numbers.forEach(new Consumer() { + @Override + public void accept(Integer t) { + System.out.print(t + " "); + } + }); + System.out.println(); + } + + public static void main(String[] args) { + printArrayWithIterator(); + + printArrayWithIndices(); + + printArrayWithLambdas(); + } +} diff --git a/09_JavaFP/src/net/hypki/wmi/javafp/FunctionChaining.java b/09_JavaFP/src/net/hypki/wmi/javafp/FunctionChaining.java new file mode 100644 index 0000000..52320e9 --- /dev/null +++ b/09_JavaFP/src/net/hypki/wmi/javafp/FunctionChaining.java @@ -0,0 +1,39 @@ +package net.hypki.wmi.javafp; + +import java.util.function.Function; +import java.util.logging.Logger; + +public class FunctionChaining { + + static Logger logger = Logger.getLogger(FunctionChaining.class.getName()); + + private static Function multiply = x -> x * 2; + + private static Function add = x -> x + 2; + + private static Function logOutput = x -> { + logger.info("Data:" + x); + return 0; + }; + + public static void execute(Integer input) { + Function pipeline = multiply + .andThen(add) + .andThen(logOutput); + pipeline.apply(input); + } + + public static void execute2(Integer input) { + multiply + .andThen(add) + .andThen(logOutput) + .apply(input); + } + + public static void main(String[] args) { + execute(10); + + execute2(10); + } + +} diff --git a/09_JavaFP/src/net/hypki/wmi/javafp/ImperativeVsDeclarative.java b/09_JavaFP/src/net/hypki/wmi/javafp/ImperativeVsDeclarative.java new file mode 100644 index 0000000..6507983 --- /dev/null +++ b/09_JavaFP/src/net/hypki/wmi/javafp/ImperativeVsDeclarative.java @@ -0,0 +1,70 @@ +package net.hypki.wmi.javafp; + +import java.util.Arrays; +import java.util.List; + +public class ImperativeVsDeclarative { + public static void imperative() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + int result = 0; + for (Integer n : numbers) { + if (n % 2 == 0) { + result += n * 2; + } + } + System.out.println(result); + } + + public static void declarative() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + System.out.println(numbers + .stream() + .filter(number -> number % 2 == 0) // 1. + .mapToInt(e -> e * 2) // Closure + .sum()); + + // 1. Lambda expressions: A Lambda expression is an anonymous method that has mutability at very minimum and it has only a parameter list and a body. + + // 2. in the above code of declarative style, every function is a pure function and pure functions don’t have side effects. + + // 3. lambdas are stateless and closure has immutable state. It means in any circumstances, the closure could not be mutable. + } + + public static void immutable() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + int factor = 2; + System.out.println(numbers + .stream() + .filter(number -> number % 2 == 0) + .mapToInt(e -> e * factor) + .sum()); + } + + public static void NOTimmutable() { + List numbers = Arrays.asList(11, 22, 33, 44, 55, 66, 77, 88, 99, 100); + + int factor = 2; + System.out.println(numbers + .stream() + .filter(number -> number % 2 == 0) + .mapToInt(e -> e * factor) + .sum()); +// factor = 3;// uncomment this + + // * the variable factor is by default being considered as final. + // * we should never try mutating any variable which is used inside pure functions == that would violate pure functions rules + // which says pure function should neither change anything nor depend on anything that changes + } + + public static void main(String[] args) { + imperative(); + + declarative(); + + immutable(); + NOTimmutable(); + } +} diff --git a/09_JavaFP/src/net/hypki/wmi/javafp/Parallel.java b/09_JavaFP/src/net/hypki/wmi/javafp/Parallel.java new file mode 100644 index 0000000..ec5ff7f --- /dev/null +++ b/09_JavaFP/src/net/hypki/wmi/javafp/Parallel.java @@ -0,0 +1,94 @@ +package net.hypki.wmi.javafp; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class Parallel { + + public static void main(String[] args) { + // forEach + System.out.println("Printing list: "); + Arrays + .asList(1,2,3) + .forEach(System.out::println); // Consumer + // print output -> 1 2 3 + + + // map + System.out.println("Computing squares (with limit and sort): "); + List numbers = Arrays.asList(2,3,4,5); + numbers.stream() + .map(x -> x *x) // Function + .sorted() + .limit(2) + .collect(Collectors.toList()) + .forEach(System.out::println);; + // print output -> [4, 9] + + // filter + System.out.println("Filtering list of strings: "); + List names = Arrays.asList("Sally", "Harry", "Sephora"); + names + .stream() + .filter(s -> s.startsWith("S")) // Predicate + .collect(Collectors.toList()) + .forEach(System.out::println);; + // print output -> [Sally, Sephora] + + // sorted + System.out.println("Sorting names: "); + names.stream() + .sorted() + .collect(Collectors.toList()) + .forEach(System.out::println);; + // print output -> [Harry, Sally, Sephora] + + // reduce + System.out.println("Printing even numbers: "); + numbers.stream() + .filter(x -> x % 2 == 0) + .collect(Collectors.toList()) + .forEach(System.out::println); + + int even = numbers.stream() + .filter(x -> x % 2 == 0) // Predicate + .reduce(4, Integer::sum); // BinaryOperator which extends BiFunction + // print output -> 10 + System.out.println("Sum of even numbers (+4 initial value): " + even); + + // max + int maxN = numbers + .stream() + .max(Integer::compare) + .get(); // Comparator + // print output -> 5 + System.out.println("Max value: " + maxN); + + // min + int minN = numbers + .stream() + .min(Integer::compare) + .get(); // Comparator + // print output -> 2 + System.out.println("Min value: " + minN); + + // skip + System.out.println("Skipping first number: "); + numbers + .stream() + .skip(1) + .collect(Collectors.toList()) + .forEach(System.out::println);; + // print output -> [3,4,5] + + System.out.println("Computing squares in parallel: "); + numbers.stream() + .parallel() // add this line here + .map(x -> x *x) + .sorted() + .limit(2) + .collect(Collectors.toList()) + .forEach(System.out::println);; + } +} diff --git a/09_JavaFP/src/net/hypki/wmi/javafp/RunnableFunctionalProgramming.java b/09_JavaFP/src/net/hypki/wmi/javafp/RunnableFunctionalProgramming.java new file mode 100644 index 0000000..6c23953 --- /dev/null +++ b/09_JavaFP/src/net/hypki/wmi/javafp/RunnableFunctionalProgramming.java @@ -0,0 +1,33 @@ +package net.hypki.wmi.javafp; + +import java.util.Arrays; +import java.util.List; + +public class RunnableFunctionalProgramming { + + public static void runnableWithoutFunProgramming() { + Runnable r = new Runnable() { + public void run() { + System.out.println("Running in Runnable thread"); + } + }; + + r.run(); + System.out.println("Running in main thread"); + + } + + public static void runnableWithFunProgramming() { + // lambda expression + Runnable r = () -> System.out.println("Running in Runnable thread"); + + r.run(); + System.out.println("Running in main thread"); + } + + public static void main(String[] args) { + runnableWithoutFunProgramming(); + + runnableWithFunProgramming(); + } +}