본문 바로가기

학교 공부/프로그래밍원리

PART 2 - Object-Oriented Programming (1)

Sub Type Polymorphism

A가 B의 subtype이면 A가 B보다 더 구체적인 것.

(B를 그대로 상속 받고 --> 다음 A가 자체적으로 더 구체화 한게 있다는 의미로 받아드리면 됨)

따라서 B에 대해서 정의된 모든 함수에 대해서 A도 사용해도 된다. (B에 정의된 것은 모두 A에 기본적으로 정의되어 있기 때문이다.)

 

 

simplification using Argument Members

class MyList[A](v:A, nxt:Option[MyList[A]]){
	val value:A = v
    val next:Option[MyList[A]] = nxt
}



class MyList[A](val value:A, val next:Option[MyList[A]]){ }

 

 

 

type T1 = {val a:Int} => {val b:String}
type T2 = {val aa:Int; val bb:String}

def f(s:{val a:Int}):{val b: String}={
  object result{
    val b = "result"
  }
  result
}
val what = f _

def fun(x:T1) = x
fun(what)


def foo(s:{val a:Int; val b:Int}):{val x:Int; val y:Int} = {
  object tmp{
    val x=s.b
    val y=s.a
  }
  tmp
}
val gee:{val a:Int; val b:Int; val c:Int} => {val x:Int} = foo _


 

 

 

 

 

Nominal Sub Typing

a.k.a. Inheritance

 

class foo_type(x:Int, y:Int) {
	val a = x
    def b = a+y
    def f(z:Int):Int = b+y+z
}

class gee_type(x:Int) extends foo_type(x+1,x+2) {
	override def f(z:Int) = b+z
    val c:Int = f(x) + b
}

(new gee_type(30)).c
//

 

 

 



Define "My Tree[A]" using sub class.

 

class MyTree[A](v:A, lt:Option[MyTree[A]], rt:Option[MyTree[A]]){
	val value = v
    val left = lt
    val right = rt
}

type YourTree[A] = Option[MyTree[A]]
sealed abstract class MyTree[A]
case class Empty[A]() extends MyTree[A]
case class Node[A](value:A, left:MyTree[A], right:MyTree[A]) extends MyTree[A]

val t:MyTree[A] = Node(3,Node(4,Empty(),Empty()),Empty())

t match {
	case Empty() => 0
    case Node(v,l,r) => v
}

 

--> Abstract Class : Interface

: Can be used to abstract away the implementation details.

 

"Abstract classes for interface

Concrete sub-classes for Implementaion"

 

 

1) Abstract Class : Interface

abstract class Iter[A]{
    def getValue:Option[A]
    def getNext:Iter[A]
}

def sumElements[A](f:A=>Int)(xs:Iter[A]):Int={
    xs.getValue match {
        case None => 0
        case Some(n) => f(n) + sumElements(f)(xs.getNext)
    }
}

def sumElementsld(xs:Iter[Int]) = sumElements((x:Int)=>x)(xs)

 

2) Concrete Class : Implementaion

sealed abstract class MyList[A] extends Iter[A]
case class MyNil[A]() extends MyList[A] {
    def getValue = None
    def getNext = throw new Exception("...")
}
case class MyCons[A](hd:A, tl:MyList[A]) extends MyList[A]{
    def getValue = Some(hd)
    def getnext = tl
}

val t1 = MyCons(3, MyCons(5,MyCons(7,MyNil())))