Skip to content

Instantly share code, notes, and snippets.

@Vilkina
Created February 11, 2020 07:14
Show Gist options
  • Save Vilkina/e13dec3615f12df30359bced6f8e8c04 to your computer and use it in GitHub Desktop.
Save Vilkina/e13dec3615f12df30359bced6f8e8c04 to your computer and use it in GitHub Desktop.
package ziolist
import zio.{ ZEnv, ZIO }
import zio._
sealed trait MyList[+ A] {
def head: Option[A]
def tail: MyList[A]
def isEmpty: Boolean
def add[B >: A](element: B): MyList[B]
final def setHead[B >: A](head: B):MyList[B] = ???
final def drop(n: Int): MyList[A] = if (n == 0) this else tail drop n-1
final override def toString: String = MyList.printElements(this)
final def map[B](f: A => B):MyList[B] = this match {
case Empty => Empty
case Cons(head, tail) => Cons(f(head), tail.map(f))
}
}
object MyList {
def apply[A](elements:A*):MyList[A] = elements.foldRight[MyList[A]](Empty)(Cons.apply)
def mkString[A](list: MyList[A])(left: String, sep: String, right: String): String = {
def interleave(list: MyList[A]): String =
list match {
case Empty => ""
case Cons(e0, Empty) => left + e0 + sep + right
case Cons(e0, tail) => e0 + interleave(tail)
}
left + interleave(list) + right
}
def printElements[A](value: MyList[A]): String =
mkString(value)("[", " ", "]")
}
object Empty extends MyList[Nothing] {
def head: Option[Nothing] = None
def tail: MyList[Nothing] = this
def isEmpty: Boolean = true
def add[B](element: B): MyList[B]= Cons(element, Empty)
}
case class Cons[+A](h: A, t: MyList[A]) extends MyList[A] {
def head: Option[A] = Some(h)
def tail: MyList[A] = t
def isEmpty: Boolean = false
def add[B >: A](element: B): MyList[B] = Cons(element, this)
}
object ListTest extends zio.App {
def println[A](x: A): ZIO[zio.console.Console, Nothing, Unit] =
zio.console.putStrLn(x match {
case None => "empty"
case Some(a) => a.toString
case a => a.toString
})
override def run(args: List[String]): ZIO[ZEnv, Nothing, Int] = {
for {
listVar <- Ref.make(MyList(1,2,3))
list <- listVar.get
_ <- println(list)
_ <- listVar.update(_.add(4))
_ <- listVar.get >>= println
} yield {
0
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment