Skip to content

Instantly share code, notes, and snippets.

@tfausak
Last active August 29, 2015 14:05
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 tfausak/47c566fd1642d2deb255 to your computer and use it in GitHub Desktop.
Save tfausak/47c566fd1642d2deb255 to your computer and use it in GitHub Desktop.

Converting a binary string to a number

Haskell

https://github.com/tfausak/exercism-solutions/blob/master/haskell/binary/Binary.hs

module Binary
( toDecimal
) where

import Data.List (foldl')

toDecimal :: String -> Int
toDecimal = convert fromBinary 2 where
    fromBinary = fromEnum . ('1' ==)

convert :: (Char -> Int) -> Int -> String -> Int
convert fromBase radix string = foldl' accumulate 0 values where
    values = map fromBase string
    accumulate number digit = number * radix + digit

Clojure

https://github.com/AaronLasseigne/exercism-answers/blob/master/clojure/binary/binary.clj

(ns binary)

(defn- bit->int [bit]
  (if (= bit \1) 1 0))

(defn- binary->decimal [shift bit]
  (bit-shift-left bit shift))

(defn to-decimal [binary]
  (->> binary
       (map bit->int)
       (reverse)
       (map-indexed binary->decimal)
       (reduce +)))

Converting a number to Roman numerals

Haskell

https://github.com/tfausak/exercism-solutions/blob/master/haskell/roman-numerals/Roman.hs

module Roman
( numerals
) where

import Data.Map (fromList, lookupLE)
import Data.Maybe (maybe)

numerals :: Int -> String
numerals n = maybe "" numerals' pair where
    numerals' (value, symbol) = symbol ++ numerals (n - value)
    pair = lookupLE n values
    values = fromList
        [ (1000,  "M")
        , ( 900, "CM")
        , ( 500,  "D")
        , ( 400, "CD")
        , ( 100,  "C")
        , (  90, "XC")
        , (  50,  "L")
        , (  40, "XL")
        , (  10,  "X")
        , (   9, "IX")
        , (   5,  "V")
        , (   4, "IV")
        , (   1,  "I")
        ]

Clojure

https://github.com/AaronLasseigne/exercism-answers/blob/master/clojure/roman-numerals/roman_numerals.clj

(ns roman_numerals)

(def ^:private conversions
  [[1000 "M"]
   [900 "CM"]
   [500 "D"]
   [400 "CD"]
   [100 "C"]
   [90 "XC"]
   [50 "L"]
   [40 "XL"]
   [10 "X"]
   [9 "IX"]
   [5 "V"]
   [4 "IV"]
   [1 "I"]])

(defn- amount->numerals [[output total] [amount numeral]]
  (let [times (quot total amount)]
    [(apply str output (repeat times numeral))
     (rem total amount)]))

(defn numerals [number]
  (->> conversions
       (reduce amount->numerals ["" number])
       (first)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment