Created
March 30, 2016 16:10
-
-
Save lucamolteni/4315d0a80892f81ae04ece26572e74d5 to your computer and use it in GitHub Desktop.
Without state monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Main where | |
| import Lib | |
| import Data.Maybe | |
| data Product = Product String | |
| deriving (Show, Eq) | |
| data ProductInfo = ProductInfo Product Int | |
| deriving (Show, Eq) | |
| data VendingMachine = VendingMachine [ProductInfo] Int String | |
| deriving (Show) | |
| initVendingMachine = VendingMachine [] 0 "init" | |
| product1 = Product "coffee" | |
| productInfo1 = ProductInfo product1 1 | |
| charge :: VendingMachine -> Int -> VendingMachine | |
| charge (VendingMachine info currentCash state) cash = | |
| VendingMachine info (currentCash + cash) "Thanks!" | |
| addProductInfo :: VendingMachine -> ProductInfo -> VendingMachine | |
| addProductInfo (VendingMachine info currentCash state) newProduct = | |
| VendingMachine (info ++ [newProduct]) currentCash "Thanks!" | |
| choose :: VendingMachine -> ProductInfo -> (VendingMachine, Either String Product) | |
| choose vm@(VendingMachine infos currentCash state) productInfo = | |
| let chosen = chooseProductInfo productInfo currentCash infos in | |
| case chosen of | |
| Nothing -> (vm, Left "Product not found") | |
| Just p@(ProductInfo product price) -> | |
| let newVendingMachine = VendingMachine infos (currentCash - price) state in | |
| (newVendingMachine, Right product) | |
| chooseProductInfo :: ProductInfo -> Int -> [ProductInfo] -> Maybe ProductInfo | |
| chooseProductInfo currentProduct currentCash infos = | |
| listToMaybe $ filter (\p -> p == currentProduct && isEnough currentCash p) infos | |
| isEnough :: Int -> ProductInfo -> Bool | |
| isEnough current (ProductInfo p i) = current > i | |
| main :: IO () | |
| main = do | |
| let charged = charge initVendingMachine 10 | |
| let withProduct = addProductInfo charged productInfo1 | |
| let res = choose withProduct productInfo1 | |
| print res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment