ios개발/함수형 프로그래밍

<함수형 프로그래밍> 3편, 유틉 강의정리, composable,transducer,reducer

studying develop 2020. 4. 17. 20:25

[https://www.youtube.com/watch?v=estNbh2TF3E]

이 강의 정리한다.

 

function comporision

- swift methods are not composable

- we should do everthing to promote composition

- curried functions are highly composable

 

왜 메소드가 not composable인가 말해본다. 

음 근데 난 컴포저블이 뭔지 모르겠는데;

 

import Foundation
 
extension Int {
    func square () -> Int{
        return self * self
    }
    func incr() -> Int{
        return self + 1
    }
}

3.square().incr()
let xs = Array(1...100)

map(xs,Int.square)

func square ( x : Int ) -> Int{
    return x * x
}
func incr( x: Int) -> Int{
    return x + 1
}

map(xs,square)

infix operator |> {associativity left}
func |> <A,B> (x:A, f: A -> B) ->B {
    return f(x)
}

func |> <A,B,C>(f: A->B,g:B->C) -> (A->C){
    return { a in
        return g(f(a))
    }
}

//piping
3 |> square |> incr
3 |> (sqaure |> incr)


// map(source : C, transform : C.Generator.Element) -> T)

func map<A,B> (f: A->B) -> [A] -> [B] {
	return {xs in
    	retur map(xs,f)
     }
}

xs |> map(square) |> map(incr)
xs |> map(square | > incr)




//filter(source : S, includeElement : (S.Generator.Element) -> Bool)

func fliter<A> (p:A-> Bool) -> [A] -> [A] {
	return { xs in
    	return filter(xs,p) }}
        
func is Prime(p: Int)->Bool{
	if p <=1 {return false}
    if p<= 3 {return true}
    for i in 2...Int(sqrtf(Float(p))){
    	if p % i == 0 { return false}
    }
    return true
}








 

 

 

Makes array operations highly composable이라는 말이, 이미 존재하는 함수들인 map,fliter,reduce등을 이용해 충분히 조합해 낼수 있다는 말같음. 커스텀 오퍼레이션 없이.

 

 

 

대부분의 배열 다루는건 reduce로 가능하다는데....

 

filter, take, flatten, map을 모두 reduce로 표현했다. flatten도 자주 나오네 이게 뭘까.

 

composable이라는게 뭐지??

reducer는 그냥 저런 모양이라함, transducer는 리듀서를 갖고 리듀서를 리턴하는 형태를 트랜듀서라함.

 

둘다 일단 뭔지는 알겠다.?.

 

일단 모르는 개념 단어 많이 나오긴 하는데, accum ,x in  이 부분도 내가 클로저 잘 모르는거 같아서 다시 찾아봤다. 클로저는 새로운 글에서 정리한다.