Adding 2 Int Lists Together F#

前端 未结 2 1440
清歌不尽
清歌不尽 2021-01-19 06:21

I am working on homework and the problem is where we get 2 int lists of the same size, and then add the numbers together. Example as follows.

    vecadd [1;2         


        
2条回答
  •  独厮守ぢ
    2021-01-19 06:43

    You can map over both lists together with List.map2 (see the docs) It goes over both lists pairwise and you can give it a function (the first parameter of List.map2) to apply to every pair of elements from the lists. And that generates the new list.

     let a = [1;2;3]
     let b = [4;5;6]
    
     let vecadd  = List.map2 (+)
    
     let result  = vecadd a b
     printfn "%A" result
    

    And if you want't to do more work 'yourself' something like this?

    let a = [1;2;3]
    let b = [4;5;6]
    
    let vecadd l1 l2 = 
        let rec step l1 l2 acc = 
            match l1, l2 with
                | [],  [] -> acc
                | [], _ | _, [] -> failwithf "one list is bigger than the other"
                | h1 :: t1, h2 :: t2 -> step t1 t2 (List.append acc [(h1 + h2)])
        step l1 l2 []
    let result  = vecadd a b
    printfn "%A" result
    

    The step function is a recursive function that takes two lists and an accumulator to carry the result.

    • In the last match statement it does three things
      • Sum the head of both lists
      • Add the result to the accumulator
      • Recursively call itself with the new accumulator and the tails of the lists
    • The first match returns the accumulator when the remaining lists are empty
    • The second match returns an error when one of the lists is longer than the other. The accumulator is returned as the result when the remaining lists are empty.

    The call step l1 l2 [] kicks it off with the two supplied lists and an empty accumulator.

提交回复
热议问题