F P in Scala
x1(井上 ゆり)
@iyunoriue
unctional
rogramming
$> ?
$> ?
GPU Rust WebAssembly & Scala!
$> ?
❤
$> GitHub?
https://github.com/x1-
$> Twitter?
@iyunoriue
$> URL?
http://x1.inkenkun.com/
Functional Programming in Scala
Scalaz
MEAP
https://www.amazon.co.jp/dp/1617290653
https://www.amazon.co.jp/dp/4844337769/
Scala
❤
p.19
We strongly suggest that you download the exercise
source code and do the exercises as you go through
each chapter. Exercises, hints, and answers are all
available at https://github.com/fpinscala/fpinscla.
https://github.com/fpinscala/fpinscla
Functional Programming in Scala
Q1.
List
List
Q1.
package fpinscala.datastructures



sealed trait List[+A]

case object Nil extends List[Nothing]

case class Cons[+A](head: A, tail: List[A]) extends List[A]



object List {

def sum(ints: List[Int]): Int = ints match {

case Nil => 0

case Cons(x,xs) => x + sum(xs)

}



def apply[A](as: A*): List[A] =

if (as.isEmpty) Nil

else Cons(as.head, apply(as.tail: _*))

}
List Cons
val x = List(1,2,3,4,5) match {

case Cons(x, Cons(2, Cons(4, _))) => x
case Nil => 42
case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)
case _ => 101
}
package fpinscala.datastructures



sealed trait List[+A]

case object Nil extends List[Nothing]

case class Cons[+A](head: A, tail: List[A]) extends List[A]



object List {

def sum(ints: List[Int]): Int = ints match {

case Nil => 0

case Cons(x,xs) => x + sum(xs)

}



def apply[A](as: A*): List[A] =

if (as.isEmpty) Nil

else Cons(as.head, apply(as.tail: _*))

}
val x = List(1,2,3,4,5) match {

case Cons(x, Cons(2, Cons(4, _))) => x

case Nil => 42

case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)

case _ => 101
}
List
A1.
scala> List.x
res0: Int = 3
val x = List(1,2,3,4,5) match {

case Cons(x, Cons(2, Cons(4, _))) => x

case Nil => 42

case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)

case _ => 101
}
Q2. drop & dropWhile
drop
dropWhile
Q2. drop & dropWhile
drop
dropWhile
def drop[A](l: List[A], n: Int): List[A]
def dropWhile[A](l: List[A], f: A => Boolean): List[A]
A2.
drop
def drop[A](l: List[A], n: Int): List[A] =

if (n <= 0) l

else l match {

case Nil => Nil

case Cons(_,t) => drop(t, n-1)

}
dropWhile
def dropWhile[A](
l: List[A],
f: A => Boolean
): List[A] =

l match {

case Cons(h,t) if f(h) => dropWhile(t, f)

case _ => l

}
Q3. foldRight
foldRight
Q3. foldRight
foldRight
def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B
A3.
foldRight
@annotation.tailrec

def foldRight[A,B](
as: List[A], z: B
)(f: (A, B) => B): B = as match {

case Nil => z

case Cons(x,xs) => f(x, foldRight(xs, z)(f))

}
@annotation.tailrec
Functional Programming in Scala
❤
Thank you for listening!

FP in scalaで鍛える関数型脳