ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Pattern Match 조합 - Email 주소 예제
    scala/basic 2021. 7. 27. 17:49

    문제

    email 의 username 부분이 동일한 문자열로 2번 반복되면서 모두 대문자인지 여부를 확인할 수 있는 아래 함수를 작성하라

    def userTwiceUpper(s: String): String
    
    // 호출 결과 예시
    userTwiceUpper("DIDI@hotmail.com") // match: DI in domain hotmail.com
    userTwiceUpper("DIDO@hotmail.com") // no match
    userTwiceUpper("didi@hotmail.com") // no match

     

    Code

    "Programming in Scala" 책에 나오는 코드

    object PatternMatchTest {
      object Email {
        def apply(user: String, domain: String): String = user + "@" + domain
        def unapply(str: String): Option[(String, String)] = {
          val parts = str.split("@")
          if (parts.length == 2) Some((parts(0), parts(1))) else None
        }
      }
    
      object Twice {
        def apply(s: String): String = s + s
        def unapply(s: String): Option[String] = {
          val length = s.length / 2
          val half   = s.substring(0, length)
          if (half == s.substring(length)) Some(half) else None
        }
      }
    
      object UpperCase {
        def unapply(s: String): Boolean = s.toUpperCase == s
      }
    
      def userTwiceUpper(s: String): String = s match {
        case Email(Twice(x @ UpperCase()), domain) => "match: " + x + " in domain " + domain
        case _                                     => "no match"
      }
    
      def main(args: Array[String]): Unit = {
        val result = userTwiceUpper("DIDO@hotmail.com")
        println(result)
      }
    }

     

    설명

    def userTwiceUpper(s: String): String = s match {
        case Email(Twice(x @ UpperCase()), domain) => "match: " + x + " in domain " + domain
        case _                                     => "no match"
    }
    
    // 분석을 해 보면
    // step1
    s match {
        case Email(user, domain) => ???
    }
    
    //  이후 user 가 특정 문자열로 2번 반복 되는지 체크가 필요
    // step2
    user match {
        case Twice(x) => ???
    }
    
    // 위의 step1, step2 조합하면
    // step3
    s match {
        case Email(Twice(x), domain) => ???
    }
    
    // x 가 UpperCase 인지 체크가 필요한데
    // step4
    x match {
        case UpperCase() => ???
    }
    
    // step3 과 step4 를 조합하면
    // 반복되는 문자열 획득을 위해 x @ UpperCase() 로 표현
    s match {
        case Email(Twice(x @ UpperCase())) => ???
    }

    'scala > basic' 카테고리의 다른 글

    apache poi 를 사용해 scala 에서 Excel 파일 읽기  (0) 2021.10.14
    Scala State Monad  (3) 2021.08.03
    enum 을 사용한 모델링  (0) 2021.07.23
    typeclass 는 언제 사용하면 좋을까?  (0) 2021.06.09
    Dark Syntax Sugar  (0) 2021.05.23

    댓글

Designed by Tistory.