IT_Programming/Dev Libs & Framework

[펌] java. google Guava 라이브러리를 사용해서 함수형 프로그래밍(Functional Programming) 시도하기

JJun ™ 2015. 2. 23. 23:17

 


 출처

 : http://blog.acidraincity.com/2015/02/java-google-guava-functional-programming.html


 




구글 Guava 라이브러리를 이용해 함수형 프로그래밍을 시도해 보려고 작성한 예제 코드입니다.


 // Arrays 클래스의 public static <t> List<t> asList(T... a); 메소드를 이용해 단일 원소 리스트를
 // 생성합니다.

 // 이렇게 생성된 리스트는 원소의 변경(set)이 가능하나 추가(add),삭제(remove)는 불가능하게
 // 됩니다.

 // Mutable한 객체상태를 참조할 수 있는 ObjectHolder로 이용하고자 하는 의도입니다.
 final List< Optional< String > > l = Arrays.asList( Optional.< String >absent() );
 
 final Predicate< Integer > p = new Predicate< Integer >()

 {
          @Override
          public boolean apply( Integer input ){
                    return input == 3;
          } //method
 };
 
 final Function< Optional< String >, Integer > f = new Function< Optional< String >, Integer >()

 {
          @Override
          public Integer apply( Optional< String > input ){
                    return Integer.parseInt( input.or( "0" ) ) + 2;
          } //method
 };
 
 new Thread()

 {
          @Override
          public void run()

          {
                    synchronized( l )

                   {
                     // 상태와 가변 데이터에 대한 처리는 사실 함수형 프로그램에서 지양하는 내용입니다.
                              l.set( 0, Optional.of( "1" ) );
                    } //sync
 
                    boolean ok = p.apply( f.apply( l.get( 0 ) ) );
                    System.out.println( ok );//true
          } //method
 }.start();

 

안드로이드 스튜디오에서 Guava 라이브러리를 사용하려면 gradle 설정에 다음을 추가하면 됩니다.

 compile 'com.google.guava:guava:18.0'
 compile 'com.google.code.findbugs:jsr305:2.0.2'

 


그리고 proguard 설정에는 다음 내용을 추가해 주세요.

 -dontwarn sun.misc.Unsafe
 -dontwarn com.google.common.collect.MinMaxPriorityQueue

 


functional programming에 대한 개념 설명은 아래 URL을 참고하세요.
http://ko.wikipedia.org/wiki/%ED%95%A8%EC%88%98%ED%98%95_%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D

Java에서의 functional programming에 대한 또다른 접근으로는 그리고 이런 것도 있습니다.

http://www.functionaljava.org

Overview

Functional Java is an open source library facilitating functional programming in Java. The library implements numerous basic and advanced programming abstractions that assist composition oriented development. Functional Java also serves as a platform for learning functional programming concepts by introducing these concepts using a familiar language.

The library is intended for use in production applications and is thoroughly tested using the technique of automated specification-based testing with ScalaCheck. Functional Java is compiled with Java 8 targeting Java 7 bytecode. The use of lambdas within the project are backported with the Retro Lambda library, supporting Java versions 5 to 8 and beyond.

Features

Functional Java provides abstractions for the following types:

  • Basic Data Structures - total and partial functions, products, unit, option, unbiased and right biased unions (either and validation).

  • Immutable Collections - array, list, vector, stream, set, map, finger tree, heterogenous list.

  • Other Abstractions - monoid, semigroup, natural, random number generator, reader, writer, state, input/output, parser, zipper, specification based testing, actors, concurrency and type conversion.

See the features page for a brief description of each of these types.

Example

Read the quick start guide for how to add FunctionalJava to your project and get started with a full example.

Functional Java includes numerous usage examples, this example maps a function over an array, adding 42 to each element (imports omitted).

final Array<Integer> a = array(1, 2, 3);
final Array<Integer> b = a.map(i -> i + 42);
arrayShow(intShow).println(b); // {43,44,45}
// combine into a single step
arrayShow(intShow).println(array(1, 2, 3).map(i -> i + 42));