Skip to content

Instantly share code, notes, and snippets.

View emmettna's full-sized avatar

Emmett Na emmettna

  • Ottawa
View GitHub Profile
@emmettna
emmettna / speared_square_cell_numbers.scala
Created March 11, 2021 02:11
calculate cell numbers hidden behind a spear line
// porivided width * height
// calculate the number of empty cells
// ex) [ ][ ][/]
// [ ][/][ ]
//. [/][ ][ ]
//
// gcd : https://gist.github.com/emmettna/702d972126d381dcceb8d8122ba7893c
def calcEmptyCells(width: Int, heght: Int): Int = width + heght - (gcd(width, heght))
@emmettna
emmettna / gcd.scala
Created March 11, 2021 02:03
greaest common divisor in scala using java math
import java.math.BigInteger
def gcd(left: Long, right: Long): Long = BigInteger.valueOf(left).gcd(BigInteger.valueOf(right)).longValue
import cats.Applicative
import cats.effect.concurrent.Ref
import cats.implicits._
import cats.effect._
class InMemorySimpleCrud[F[_]: Applicative](ref: Ref[F, Map[String, Human]])
extends SimpleCrud.Service[F] {
override def add(human: Human): F[Unit] =
ref.update(_.updated(human.name, human))
override def find(name: String): F[Option[Human]] =
final case class Human(name: String, age: Int)
trait SimpleCrud[F[_]] {
val simpleCrudService: SimpleCrud.Service[F]
}
object SimpleCrud {
trait Service[F[_]] {
def add: F[Unit]
def find(name: Name): F[Option[Human]]
}
}
val five = 5
five match {
case v if v > 5 => ???
case v if v == 5 => ???
case v if v < 5 => ???
}
// more practical example
final case class FeeInquiry(user: UserId, amount: BigDecimal, currency: Currency)
val requestedFee: Option[FeeInquiry] = ???
"1,2,3".split(",").toList match {
case first :: second :: third :: Nil => "Counting Practice"
case _ => throw new Exception("This is not what I expected")
}
val list: List[Option[Int]] = List(Some(1), None, Some(2))
val result: List[Int]=list.map( numberOpt => numberOpt match {
case Some(v) => v
case None => 0
})
final case class DummyCaseClass(value: Int)
val dummyCaseClassOpt = Option(DummyCaseClass(1))
dummyCaseClassOpt match {
case Some(DummyCaseClass(v)) => v.toString
case Some(_) => ???
case None => ???
}
// equivalent
dummyCaseClassOpt match {
case v: Some[DummyCaseClass] => v.toString
val optionValue = Option(1)
optionValue match {
case Some(v) => ???
case None => ???
}
final case class IntegerParser(value: Int)
val prasedInt = IntegerPraser(value = 1)
parsedInt match {
case IntegerParser(value) => value.toString
case _ => "Invalid Int"
}