본문 바로가기

Computer Science/Programming Language

[프로그래밍언어/ML] ML Modules - 컴도리돌이

728x90
728x90

2020/06/15 - [컴퓨터 전공 공부/프로그래밍언어론] - [프로그래밍언어/ML] pairs, lists, local bindings, benefit of no mutation - 컴도리돌이-(1)

2020/06/15 - [컴퓨터 전공 공부/프로그래밍언어론] - [프로그래밍 언어/ ML] Records, Datatypes, Case Expressions and more - 컴도리돌이-(2)

2020/06/15 - [컴퓨터 전공 공부/프로그래밍언어론] - [프로그래밍 언어론/ ML] Nested Patterns Exceptions tail Recursion -컴도리돌이-(3)

2020/06/16 - [컴퓨터 전공 공부/프로그래밍언어론] - [프로그래밍언어/ML] ML Modules - 컴도리돌이-(4)


Modules

 

SML은 모듈 시스템으로 계층적이고 조직화된 구조를 구축할 수 있다. 논리적으로 관련된 유형 그리고 값 선언 요소들을 정의할 수 있다. SML의 모듈 시스템은 네임스페이스, 추상 자료형, 구현을 정의할 수 있는 모듈을 제공한다.

 

 

-structure

 

structure는 Class와 유사하게 구현을 정의한다. 다른 점은 내부적으로 type을 정의할 수 있고, signature와 함께 정의하여 모든 것을 접근할 수 있다.

 

structure <Name>: <Signature Name> = struct <Implementation> end

 

signature 없이 structure 정의

 

structure Rat = struct (* implementation *) end

 

<example>

structure MyMathLib =
struct

fun fact x =
	if x=0
	then 1
	else x * fact(x-1)

val half_pi = Math.pi / 2

fun doubler x = x * 2

end

 

unique structure

 

: 대신 :>사용하여 unique 한 structure를 정의할 수 있다.

 

structure Rat :> RAT = struct ... end

 

Signatures

 

signature은 모듈의 한 타입이다. namespace처럼 내부에서 type을 정의할 수 있고, 내부에 정의된 모든 것은 밖에서 접근할 수 없다. 모듈은 변수들과 타입, datatypes와 exceptions이 포함될 수 있다.

 

signature <Name> = sig <Interface> end

 

<example>

signature MATHLIB =
sig
val fact : int -> int
val half_pi : real
val doubler : int -> int
end

structure MyMathLib :> MATHLIB =
struct
fun fact x = …
val half_pi = Math.pi / 2.0
fun doubler x = x * 2
end

The problem

 

signature RATIONAL_A =
sig
datatype rational = Whole of int | Frac of int*int
…

 

데이터 유형 정의를 공개함으로써 고객이 직접 'Rational1.Rational' 유형의 값을 생성함으로써 불변성을 위반하도록 허용한다.

 

- Rational1.Frac(1,0)

- Rational1.Frac(3,~2)

- Rational1.Frac(9,6)


이 중 어떤 것도 '예외', '무한 루프' 또는 '잘못된 결과'로 이어질 수 있기 때문에 모듈의 코드는 이들을 절대 반환하지 않을 것이다.

 

so hide more

 

핵심 : ADT는 고객이 직접 유형의 불변한 값을 생성할 수 없도록 구체적인 유형 정의를 숨겨야 한다. 실제로는 타입이 존재 하지만, 고객들은 그것의 정의에 대해 알지 못하게끔 만든다. (Abstract types)

 

signature RATIONAL_B =
sig
type rational
exception BadFrac
val make_frac : int * int -> rational
val add : rational * rational -> rational
val toString : rational -> string
end

 

먼저 이성적으로 만드는 유일한 방법은 'Rational1.make_frac'이다.
그 후에는 'Rational1.make_frac', Rational1.add, 'Rational1.toString'만 사용할 수 있다.
생성자와 패턴을 숨긴다. – 'Rational1.Rational'이 데이터 유형인지 여부조차 알 수 없음
 그러나 고객은 여전히 어떤 방식으로든 일부를 전달할 수 있다.

 

Two key restrictions

 

1. Deny bindings exist (val-bindings, fun-bindings, constructors)
2. Make types abstract (so clients cannot create values of them or access their pieces directly)

 

Equivalent implementations

 

추상화의 주요 목적은 다양한 구현이 동등하도록 허용하는 것이다.
– 어떤 고객도 사용 중인지 알 수 없음
– 나중에 구현을 개선/교체/선택할 수 있음
– 보다 추상적인 서명(필수 사항만 확인)으로 시작할 경우 더 쉽게 수행할 수 있음

 

 

728x90
728x90