[fn_in_js] Haskell 타입 표기법

Inhye Jeong·2020년 11월 13일
0

1. 타입 추론

x :: Number
x = 0

2. 타입 표기법

identity function

  • ts
const id<T> = (x: T) => x

type Id<T> = (x: T) => T
const id: Id = (x) => x
  • haskell

haskell에서는 소문자 a를 type으로 본다. ts에서 제네릭 T처럼..

id :: forall a. a -> a

함수를 일급객체로 다루면, 함수와 변수를 구분하지 않는다. 변수는 항상 같은 값을 리턴하는 함수로 볼 수도 있다.

R.always

always :: forall ab. a -> b -> a
always x y = x

R.apply

apply :: forall ab. (a -> b) -> a -> b

flip

  • 인자를 2개 받는 함수에 인자의 위치를 바꾸는 함수.
second :: forall ab. a -> b -> b
// second를 만들지 않고 flip을 이용해서 구현
flip :: forall abc. (a -> b -> c) -> b -> a -> c
(a -> b -> a) -> (b -> a -> a)

compose

// math
g(f(x))
// ts
compose(g, f)(x)
// haskell : g,f 타입의 함수와 x타입의 변수를 받자.
compose :: (a -> b) -> (? -> a) -> ? -> b
compose :: (b -> c) -> (a -> b) -> a -> c
compose gfx = g(fx)

pipe

// ts
pipe(f, g)(x)
// haskell
pipe :: (a -> b) -> (b -> c) -> (a -> c)
// pipe 함수를 flip에 compose를 주면? 완성.
pipe = flip compose

map

// Ramda에서의 map
map :: (a -> b) -> Array a -> Array b
map :: (a -> b) -> f a -> f b
// Array.prototype.map
// this를 ~로 표기하기도한다. 첫번째 인자
map :: Array a ~> (a -> b) -> Array b

Promise.then

// map 함수를 flip하면 아래와 같다.
then :: Promise a -> (a -> b) -> b

reduce

  • reduce로 map을 만들 수 있다.
reduce :: (a -> b -> a) -> a -> Array b -> a
profile
Frontend Engineer in @KakaoStyle

0개의 댓글