emanuel
emanuel

Reputation: 21

Standard ML : How to access column from list of list in standard ML

Suppose I have a list of list list = [[1,2,3],[4,5,6],[7,8,9]] and i want to calculate the sum of the columns. i.e The first column is [1,4,7]and its sum is 12 Second column is [2,5,8] ans sum is 15 and so on

Is there any efficient way(with less complexity) in standard ML to do this?? Please help

Upvotes: 1

Views: 105

Answers (1)

Andreas Rossberg
Andreas Rossberg

Reputation: 36098

For example:

fun transpose [] = []
  | transpose ([]::xss) = []
  | transpose xss = map hd xss :: transpose (map tl xss)

val sum = foldl op+ 0

val sumsOfColumns = map sum o transpose

Example use:

sumsOfColumns [[1,2,3],[4,5,6],[7,8,9]]  (* => [12, 15, 18] *)

;)

Upvotes: 2

Related Questions