Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What is going on with this article?

More than 5 years have passed since last update.

@mtoyoshi

lift関数いいすね

before

ちょっと例が微妙なのだけど、、、
指定されたn番目の値を返す関数。存在するかしないかわからないので戻り値はOptionに。

def foo[A](seq: Seq[A], n: Int): Option[A] = {
  if (!seq.isEmpty && n > 0 && n < seq.size) Some(seq(n))
  else None
}

after

Seq#liftはIntを受け取ってOptionを返す関数。
存在しないindexが与えられればNoneを返してくれるので上記のようなチェックは不要になる。

def foo[A](seq: Seq[A], n: Int): Option[A] = seq.lift(n)

PartialFunction

元はPartialFunctionのlift関数で、これを使うとPartialFunctionを親トレイトであるFunction1に持ち上げる(liftする)事ができる。

val pf: PartialFunction[Int, String] = { case n if n % 2 == 0 => "even!" }
val f: Int => Option[String] = pf.lift

Seqの他にも、PartialFunctionトレイトを持つMapとかStackとかでも使うことが出来る。

4
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
4
Help us understand the problem. What is going on with this article?