user2744489
user2744489

Reputation: 501

F# sum of a list of lists

I created my own datatype And I'm trying to create the sum of all the numbers in that datatype which is a list of lists. I don't want to use any F# libraries

My datatype

type elist = A | L of int * elist

I'm a beginner in F# and trying to grasp my head on it. I want to do this recursively. My thinking going into it is to traverse to the end of the list and start an sum and go back to the front and add each one.

example:

let l = L(4, L(3, L(6, L(3, A))))

that should return

val it : int 16

Here's my code and I know it is wrong:

let rec sum l = 
   let a = 0
   match l with
   | A -> 0
   | L(head,A) -> head 
   | L(head,tail) -> sum tail + a

Upvotes: 1

Views: 570

Answers (1)

Rob Lyndon
Rob Lyndon

Reputation: 12661

You're nearly there. All you need is to lose the a:

let rec sum l = 
   match l with
   | A -> 0
   | L(head,A) -> head 
   | L(head,tail) -> head + sum tail

Then evaluating sum l when l = L(4, L(3, L(6, L(3, A)))) gives

val it : int = 16

as required.

Upvotes: 3

Related Questions