Skip to content

Instantly share code, notes, and snippets.

@xmeta
Last active April 8, 2022 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmeta/2f1e9ca0e945aaa59f3326eadbdece84 to your computer and use it in GitHub Desktop.
Save xmeta/2f1e9ca0e945aaa59f3326eadbdece84 to your computer and use it in GitHub Desktop.
module Main exposing (..)
import Html exposing (text)
import String
import Char
toHex : Int -> String
toHex n =
let
hex = String.toUpper(toRadix n)
in
if String.length hex == 1 then
"0" ++ hex
else
hex
toRadix : Int -> String
toRadix n =
let
getChr c =
if c < 10 then
String.fromInt c
else
String.fromChar <| Char.fromCode (87 + c)
in
if n < 16 then
getChr n
else
(toRadix (n // 16)) ++ (getChr (modBy 16 n))
type Color
= Red
| Green
| Blue
| Rgb { r: Int, g: Int, b: Int }
colorToHex : Color -> String
colorToHex color =
case color of
Red ->
"#FF0000"
Green ->
"#00FF00"
Blue ->
"#0000FF"
Rgb {r, g, b} ->
"#" ++ (toHex r) ++ (toHex g) ++ (toHex b)
main = text(colorToHex(Rgb{r = 255, g = 255, b = 255}))
@enum ColorBase red blue green
struct Rgb
r::UInt8
g::UInt8
b::UInt8
end
Color = Union{ColorBase,Rgb}
function to_s(c::Color)::String
if c == red
return "#FF0000"
elseif c == blue
return "#00FF00"
elseif c == green
return "#0000FF"
elseif typeof(c) == Rgb
hex = (x) -> uppercase(string(x, base=16, pad=2))
return string("#", hex(c.r), hex(c.g), hex(c.b))
end
end
println(to_s(Rgb(255, 255, 255)))
println(to_s(red))
println(to_s(blue))
println(to_s(green))
type color {
Red
Green
Blue
Rgb( r : int, g : int, b: int )
}
fun to_s(c: color) {
match(c) {
Red -> "#FF0000"
Green -> "#00FF00"
Blue -> "#0000FF"
Rgb(r,g,b) -> "#"+showHex(r,2)+showHex(g,2)+showHex(b,2)
}
}
fun main() {
c = Rgb(255,1,255)
println(to_s(c))
}
type color = Red | Green | Blue | Rgb({r: int, g: int, b: int})
let numToHex = i =>
"00" ++
Js.Int.toStringWithRadix(i, ~radix=16)
->Js.String2.slice(~from=-2, ~to_=Js.Int.max)
->Js.String.toUpperCase
let toHex = color =>
switch color {
| Red => "#FF000"
| Green => "#00FF00"
| Blue => "#0000FF"
| Rgb({r, g, b}) => "#" ++ numToHex(r) ++ numToHex(g) ++ numToHex(b)
}
let white = Rgb({r: 255, g: 255, b: 255})
toHex(white) |> Js.log
enum Color {
case Red, Green, Blue, Rgb(r:Int, g:Int, b:Int)
func str() -> String {
switch self {
case .Red:
return "#FF0000"
case .Green:
return "#00FF00"
case .Blue:
return "#0000FF"
case let .Rgb(r, g, b):
return String(format:"#%02X%02X%02X", r, g, b)
}
}
}
let c:Color = Color.Rgb(r:255, g:255, b:255)
print(c.str())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment