본문 바로가기

Computer Science/Programming Language

[프로그래밍 언어론/ ML] Nested Patterns Exceptions tail Recursion -컴도리돌이

728x90
728x90

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

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

 


Pattern Matching

 

fun eval e =
	case e of
		Constant i => i
		| Negate e2 => ~ (eval e2)
		| Add(e1,e2) => (eval e1) + (eval e2)
		| Multiply(e1,e2) => (eval e1) * (eval e2)
        
fun eval(Constant(i)) = i
	| eval(Negate(e)) = ~ (eval e)
	| eval(Add(e1, e2)) = (eval e1)+(eval e2)
	| eval(Multiply(e1, e2)) = (eval e1)*(eval e2)

Nested patterns

 

• We can nest patterns as deep as we want
– Just like we can nest expressions as deep as we want
– Often avoids hard-to-read, wordy nested case expressions


• So the full meaning of pattern-matching is to compare a pattern against a value for the “same shape” and bind variables to the “right parts”


Exceptions

 

예외처리는 raise으로 한다.

 

fun calc (n) = if n < 0.0
               then raise Domain
               else n * 1.04
val balance = calc(~10.0)



uncaught exception Domain [domain error]
  raised at: test.sml:47.27-47.33

 

예외 핸들링은 handling으로 한다.

 

fun calc (n) = if n < 0.0
               then raise Domain
               else n * 1.04
               
val balance = calc(~10.0)
              handle Domain => ~10.0

val calc = fn : real -> real
val balance = ~10.0 : real

Tail call

 

tail-recursive는 매우 효과적인 재귀 함수이다. 

 

fun sum xs =
    case xs of
        [] => 0
        | x::xs' => x + sum xs'

fun sum xs =
    let fun aux(xs,acc) =
        case xs of
            [] => acc
            | x::xs' => aux(xs',x+acc)
    in
        aux(xs,0)
    end

 

fun rev xs =
    case xs of
        [] => []
        | x::xs' => (rev xs') @ [x]
        
fun rev xs =
    let fun aux(xs,acc) =
            case xs of
                [] => acc
                | x::xs' => aux(xs',x::acc)
        in
            aux(xs,[])
        end

 

728x90
728x90