Skip to content

Instantly share code, notes, and snippets.

@IltaySaeedi
Last active July 25, 2021 06:51
Show Gist options
  • Save IltaySaeedi/79db593976c2953a5bd1a728d6ca078c to your computer and use it in GitHub Desktop.
Save IltaySaeedi/79db593976c2953a5bd1a728d6ca078c to your computer and use it in GitHub Desktop.
Adding Items to bucket
type Item =
{ Name : string
Quantity : uint }
type Items = Item list
type Bucket =
| Items of Items
| Empty
| InvalidItemName
let newItem name quantity =
{ Name = name
Quantity = quantity }
/// If new item is not valid returns the invalid bucket
/// If bucket is empty or new item doesn't exist in the bucket, it returns bucket with new Item
/// Or updates quantity of new item
let addItem (addItemFunc: (Items -> Item -> Bucket)) (newItem : Item) (bucket: Bucket) =
match bucket, newItem.Name.ToLower().Trim(), newItem.Quantity with
| _, "", _
| InvalidItemName, _, _ ->
InvalidItemName
| _, _, 0u ->
bucket
| Empty, _, _ ->
Items [ newItem ]
| Items bucketItems, itemName, quantity ->
addItemFunc bucketItems ({Name = itemName; Quantity = quantity})
/// If Id is not unique this function returns wrong answer because
/// it adds quantity of new item to every item with the same name
let tryFindAndAdd bucketItems addedItem =
match
List.tryFind
(fun item -> item.Name.ToLower().Trim() = addedItem.Name)
bucketItems with
| None ->
Items (addedItem :: bucketItems)
| Some sameNameItem ->
let updatedItem =
{ sameNameItem with
Quantity = sameNameItem.Quantity + addedItem.Quantity}
let updatedItems =
List.map
(fun item ->
if item.Name.ToLower().Trim() = addedItem.Name then
updatedItem
else
item)
bucketItems
Items updatedItems
let partitionAndFold bucketItems addedItem =
match List.partition
(fun item -> item.Name.ToLower().Trim() = addedItem.Name)
bucketItems with
| [], bucketItems ->
Items (addedItem :: bucketItems)
| sameNameItems, otherItems ->
(List.fold
(fun acc item ->
{ acc with Quantity = acc.Quantity + item.Quantity })
addedItem
sameNameItems)
:: otherItems
|> Items
let sameNameAllInOne bucketItems addedItem =
(addedItem :: bucketItems)
|> List.groupBy
(fun item ->
item.Name.ToLower().Trim())
|> List.map
(fun (_, items) ->
List.reduce
(fun acc item ->
{ acc with Quantity = acc.Quantity + item.Quantity})
items)
|> Items
let addApples = newItem "Apples"
let addBananas = newItem "Bananas"
let mybucket =
Items ([(addApples 10u); (addApples 20u); (addBananas 30u); (addBananas 40u) ])
let tryFindAndAddItem = addItem tryFindAndAdd
let partitionAndFoldItems = addItem partitionAndFold
let sameNameItemsAllInOne = addItem sameNameAllInOne
tryFindAndAddItem (addApples 2u) mybucket
partitionAndFoldItems (addApples 2u) mybucket
sameNameItemsAllInOne (addApples 2u) mybucket
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment