smlsmlnj

How to add all elements in a list in SML


I am trying to add all elements in a given integer list and finally return an integer as its sum

Following is the code I have tried

val intList = [1,2,3,4];

fun addList (list) = 
let
  val head = List.hd list
  val tail = List.tl list
  val sum = ref 0
in
  if(list <> [])
  then sum := !sum + head
  addList(tail)
  else !sum
end;

However, I am getting the following error

Elaboration failed: Type clash. An expression of type "'a" cannot have type "(('a → 'b) → 'c → 'd) List.list" because of circularity.

I am quite new to SML/NJ What could I be doing wrong?


Solution

  • So, I was looking into a different problem and I found a solution for this one as well.

    val intList = [3,7,5,6];
    
    fun addList (list, x)=
    if list = []
    then x
    else
    let
      val head = hd(list)
    in
      addList(tl(list), x + head)
    end;
    
    
    val something = addList(intList, 0);
    

    It is similar to how the foldl operation works, but ofcourse different in terms of use.

    I didn't know we could pass an element this way as an argument to the function. This was interesting.