Skip to content

Instantly share code, notes, and snippets.

@dolegi
Last active February 6, 2017 17:02
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 dolegi/7ef37b2956d74eccbeac9115feac24c6 to your computer and use it in GitHub Desktop.
Save dolegi/7ef37b2956d74eccbeac9115feac24c6 to your computer and use it in GitHub Desktop.
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
type alias Product = { name : String, singular : String, amount : Int, price : Int }
type alias Model =
{ products : List Product, cash : Int }
model : Model
model =
{ products = [
{ name = "Tomatoes", singular = "Tomato", amount = 0, price = 10 }
, { name = "Potatoes", singular = "Potato", amount = 0, price = 5 }
, { name = "Beetroots", singular = "Beetroot", amount = 0, price = 7 }
], cash = 100 }
type Action =
Buy Product | Sell Product
updateProducts products product =
let
newProducts =
List.map (\p ->
if p.name == product.name then
product
else
p) products
in
newProducts
update : Action -> Model -> Model
update action model =
case action of
Buy product ->
{ model | products = (updateProducts model.products product), cash = model.cash - product.price }
Sell product ->
{ model | products = (updateProducts model.products product), cash = model.cash + product.price }
pluralize : String -> String -> Int -> String
pluralize singular plural quantity =
if quantity == 1 then
singular
else
plural
view model =
let
caption amount productName productSingular =
(toString amount)
++ " "
++ pluralize productSingular productName amount
productButton actionType label disable =
button [ disabled disable, onClick actionType ] [ text label ]
moneyText val =
text ("£" ++ (toString val))
getProduct productName =
List.head (List.filter (\m -> m.name == productName) model.products)
|> Maybe.withDefault { name = "", singular = "", amount = 0, price = 0 }
updateProductAmount product amountChange =
{ product | amount = product.amount + amountChange }
buySell product =
div [] [
moneyText product.price
, productButton (Buy (updateProductAmount product 1)) "Buy" ((model.cash - product.price) < 0)
, productButton (Sell (updateProductAmount product -1)) "Sell" (product.amount <= 0)
, text (caption product.amount product.name product.singular)
]
productsDisplay =
List.map (buySell) model.products
in
div []
([ h1 [] [ text "Market" ]
, div [] [ moneyText model.cash ]
] ++ productsDisplay)
main = beginnerProgram { model = model, update = update, view = view }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment