DEV Community

Discussion on: Daily Challenge #236 - RGB to Hex Conversion

Collapse
 
craigmc08 profile image
Craig McIlwrath

Haskell solution:

import Numeric (showIntAtBase)
import Data.Char (intToDigit)

clamp :: (Ord a) => a -> a -> a -> a
clamp mi ma x = minimum [maximum [x, mi], ma]

padStart :: Int -> a -> [a] -> [a]
padStart l x = until ((>=l) . length) (x:)

rgb2num :: (Int, Int, Int) -> Int
rgb2num (r, g, b) = clampColor r * 65536 + clampColor g * 256 + clampColor b
  where clampColor = clamp 0 255

rgb2hex :: (Int, Int, Int) -> String
rgb2hex n = padStart 6 '0' $ showIntAtBase 16 intToDigit (rgb2num n) ""