The sum of the two values ​​of the discriminated list F #

I have an exercise to suggest a function that sums every value of the same type from a discriminated union list as follows:

type volume =
     | Litre of float
     | Galon of float
     | Bucket of float
     | Bushel of float

let list = [Litre(20.0);Litre(30.0);Galon(2.0);Bucket(5.0);Litre(5.0);Galon(3.0)];

Where the output should look like this:

[Litre(55.0);Galon(5.0);Bucket(5.0)]

I came with part of the solution:

let rec sumSameTypes (list:volume list) =
    match list with
    | a::b::t -> if a.GetType() = b.GetType() then // and there is part where I don't know how to sum two of these elements
    | [] -> failwith "EMPTY"
+4
source share
2 answers

Since this is more like a learning question, I will try to give some advice, not a complete answer.

GetType ( ) , , . , , , :

match a with
| Litre(n) -> // Do something with 'n'
// Add all the other cases here

, , , - , - , , , , .

let rec sumSameTypes (list:volume list) : float * float * float * float =
    match list with
    | [] -> 
        // For empty list, we just have 0 of everything
        0.0, 0.0, 0.0, 0.0
    | x::xs ->
        // For non-empty list, process the rest recrsively
        // and pattern match on `x` to figure out which of 
        // the numbers you need to increment

, , . , - ( ), , :

type Unit = Litre | Galon | Bushel | Bucket
type Volume = { Amount : float; Unit : Unit }

, Map<Unit, float> .

+7

:

let sum lst =
    let rec loop acc = function
        | []   -> acc
        | h::t -> loop (acc + h) t
    loop 0.0 lst

4 ( ):

let sumByType lst =
    let rec loop litre gallon bucket bushel = function
        | []   -> // return a new volume list built using the accumulators values 
        | h::t -> // recursive calls with modified accumulators according to h type
    loop 0.0 0.0 0.0 0.0 lst
0

Source: https://habr.com/ru/post/1668416/


All Articles