Skip to content

Instantly share code, notes, and snippets.

@mitsuji
Last active January 5, 2016 09:13
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 mitsuji/237e6fcf96fd8db73bbb to your computer and use it in GitHub Desktop.
Save mitsuji/237e6fcf96fd8db73bbb to your computer and use it in GitHub Desktop.
import Data.List (foldl')
import Control.Monad.Reader (Reader,runReader,ask)
import Control.Monad (foldM)
main = do
print $ total 0.08 [(108,True,2),(200,False,1),(324,True,2),(400,False,1)]
print $ totalG [(108,True,2),(200,False,1),(324,True,2),(400,False,1)]
print $ totalR 0.08 [(108,True,2),(200,False,1),(324,True,2),(400,False,1)]
toTaxIncluded :: Float -> Float -> Float
toTaxIncluded taxRate price = price * (1.00 + taxRate)
fromTaxIncluded :: Float -> Float -> Float
fromTaxIncluded taxRate tiPrice = tiPrice / (1.00 + taxRate)
total :: Float -> [(Float,Bool,Int)] -> Float
total taxRate xs =
let subTotal = foldl' step 0.0 xs
in toTaxIncluded taxRate subTotal
where
step acc (price,taxin,quan) = acc + (unitPrice taxin price) * (fromIntegral quan)
unitPrice taxin = if taxin
then fromTaxIncluded taxRate
else id
taxRateG :: Float
taxRateG = 0.08
toTaxIncludedG :: Float -> Float
toTaxIncludedG price = price * (1.00 + taxRateG)
fromTaxIncludedG :: Float -> Float
fromTaxIncludedG tiPrice = tiPrice / (1.00 + taxRateG)
totalG :: [(Float,Bool,Int)] -> Float
totalG xs =
let subTotal = foldl' step 0.0 xs
in toTaxIncludedG subTotal
where
step acc (price,taxin,quan) = acc + (unitPrice taxin price) * (fromIntegral quan)
unitPrice taxin = if taxin
then fromTaxIncludedG
else id
toTaxIncludedR :: Float -> Reader Float Float
toTaxIncludedR price = do
taxRate <- ask
return $ price * (1.00 + taxRate)
fromTaxIncludedR :: Float -> Reader Float Float
fromTaxIncludedR tiPrice = do
taxRate <- ask
return $ tiPrice / (1.00 + taxRate)
totalR :: Float -> [(Float,Bool,Int)] -> Float
totalR taxRate xs = (`runReader` taxRate) $ do
subTotal <- foldM step 0.0 xs
toTaxIncludedR subTotal
where
step :: Float -> (Float,Bool,Int) -> Reader Float Float
step acc (price,taxin,quan) = do
up <- unitPrice taxin price
return $ acc + up * (fromIntegral quan)
unitPrice taxin = if taxin
then fromTaxIncludedR
else return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment