简体   繁体   中英

F# adding lists

How would I go about adding sub-lists.

For example, [ [10;2;10]; [10;50;10]] ----> [20;52;20] [ [10;2;10]; [10;50;10]] ----> [20;52;20] that is 10+10, 2+50 and 10+10. Not sure how to start this.

Fold is a higher order function:

let input = [[10;2;10]; [10;50;10]]
input |> Seq.fold (fun acc elem -> acc + (List.nth elem 1)) 0

val it : int = 52

Solution 1: Recursive version

We need a helper function to add two lists by summing elements one-to-one. It is recursive and assumes that both lists are of the same length:

let rec sum2Lists (l1:List<int>) (l2:List<int>) = 
    match (l1,l2) with 
    | ([],[]) -> []                    
    | (x1::t1, x2::t2) -> (x1+x2)::sum2Lists t1 t2  

Then the following recursive function can process a list of lists, using our helper function :

let rec sumLists xs = 
    match xs with 
    | [] -> []                                // empty list
    | x1::[] -> x1                            // a single sublist
    | xh::xt -> sum2Lists xh (sumLists xt)    // add the head to recursion on tail
let myres = sumLists mylist

Solution 2: higher order function

Our helper function can be simplified, using List.map2 :

let sum2hfLists (l1:List<int>) (l2:List<int>) = List.map2 (+) l1 l2

We can then use List.fold to create an on the flow accumulator using our helper function:

let sumhfList (l:List<List<int>>) = 
    match l with 
    | [] -> []                  // empty list of sublist
    | h::[] -> h                // list with a single sublist
    | h::t -> List.fold (fun a x -> sum2hfLists a x) h t

The last match case is applied only for lists of at least two sublists. The trick is to take the first sublist as starting point of the accumulator, and let fold execute on the rest of the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM