Skip to content

Instantly share code, notes, and snippets.

View lachezar's full-sized avatar
:shipit:
Type safety lobbyist

Lachezar Yankov lachezar

:shipit:
Type safety lobbyist
View GitHub Profile
@lachezar
lachezar / currency_example.hs
Last active September 5, 2020 15:12
Currency in Haskell
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where
newtype USD = USD Int deriving (Show, Num)
newtype EUR = EUR Int deriving (Show, Num)
main :: IO ()
main = do
print $ (USD 12) + (USD 11)
@lachezar
lachezar / currency_example.scala
Last active November 30, 2020 16:07
currency_example.scala
sealed trait Currency
case object Dollar extends Currency
case object Euro extends Currency
case class Money[T <: Currency](value: Int, currency: T) {
def +(that: Money[T]): Money[T] = {
Money[T](this.value + that.value, currency)
}
}
@lachezar
lachezar / life.html
Created July 24, 2011 19:18
Game of Life (Javascript + HTML5's Canvas)
<!DOCTYPE html>
<html>
<head>
<title>Game of Life</title>
</head>
<body>
<canvas id="canvas" width="400" height="300">There should be a canvas somewhere here.... :-/</canvas>
<script type="text/javascript">
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
@lachezar
lachezar / CheckedOptional.java
Created November 15, 2023 13:11
Java Optional that forces you to deal with the missing value on compile-time level instead of the runtime.
package org.example;
import java.util.Optional;
import java.util.Random;
import java.util.function.Supplier;
class NPEChecked extends Exception implements Supplier<NPEChecked> {
private static final NPEChecked instance = new NPEChecked();
@Override
@lachezar
lachezar / IO.scala
Last active November 21, 2023 13:20
IO implementation exercise
case class IO[A](unsafeRun: () => A):
def map[B](f: A => B): IO[B] =
IO(() => f(unsafeRun()))
def flatMap[B](f: A => IO[B]): IO[B] =
IO(() => f(unsafeRun()).unsafeRun())
val io: IO[Int] = IO(() => {
println("Running side effect!!!")
@lachezar
lachezar / Monads.scala
Last active February 12, 2024 15:36
Scala 3 Monad type class for Option and Either
trait Monad[M[_]] {
def pure[A](a: A): M[A]
def flatMap[A, B](m: M[A])(f: A => M[B]): M[B]
}
enum MyOption[+T]:
case None
case Some(value: T)
given Monad[MyOption] with