Sha256: 89f401cdc95342e4aa53c4ef360ebfb4b4e23b2dac037dc6e24b86f80d757aba

Contents?: true

Size: 739 Bytes

Versions: 62

Compression:

Stored size: 739 Bytes

Contents

module Base (Error(..), rebase) where

import Control.Monad (foldM)
import Data.List     (unfoldr)
import Data.Tuple    (swap)

data Error a = InvalidInputBase | InvalidOutputBase | InvalidDigit a
    deriving (Show, Eq)

rebase :: Integral a => a -> a -> [a] -> Either (Error a) [a]
rebase ibase obase ds
    | ibase < 2 = Left InvalidInputBase
    | obase < 2 = Left InvalidOutputBase
    | otherwise = toDigits obase <$> fromDigits ibase ds
  where

    fromDigits base = foldM f 0
      where
        f acc x | x >= 0 && x < base = Right (acc * base + x)
                | otherwise          = Left (InvalidDigit x)

    toDigits base = reverse . unfoldr f
      where
        f 0 = Nothing
        f x = Just . swap $ x `divMod` base

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.179 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.178 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.177 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.176 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.175 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.174 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.173 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.172 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.171 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.170 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.169 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.167 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.166 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.165 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.164 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.163 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.162 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.161 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs
trackler-2.2.1.160 tracks/haskell/exercises/all-your-base/examples/success-standard/src/Base.hs