New for SML / NJ. Adding numbers from a list of lists

Define a function that calculates the sum of all integers in a given list of lists of integers. There is no "if-then-else" or any helper function.

I am new to functional programming and am having problems with the correct syntax with SML. To start the problem, I tried to create a function using pattern matching that simply adds the first two elements of the list. After I got this working, I was going to use recursion to add the rest of the elements. Although, I can’t even imagine this simple function for compilation.

fun listAdd [_,[]] = 0 | listAnd [[],_] = 0 | listAnd [[x::xs],[y::ys]] = x + y; 
+4
source share
3 answers
 fun listAdd [] = 0 | listAdd ([]::L) = listAdd L | listAdd ((x::xs)::L) = x + listAdd (xs::L) 

should do what you like.

Also, it seems like part of the problem with your function is that you provide the function with different names (listAdd and listAnd) in different sentences.

+2
source

You probably don't need the input int list list , but just int list * int list (a pair of int lists). Also, your function seems to return numbers, not a list of numbers. You will use recursion for this.

 fun listAdd (x::xs, y::ys) = (x + y) :: listAdd (xs, ys) | listAdd ([], _) = [] | listAdd (_, []) = [] (* The last two cases can be merged *) 

You will probably want to read a book on functional programming on the first page and beyond. Select SML / NJ Programming Notes from Riccardo Pucella if you want to get free.

0
source

For simplicity, I would say you probably want this:

 fun listAdd : (int * int) list -> int list 

Now I would simply define this as an abstraction of the unzip function:

 fun listAdd ls : case ls of [] => 0 | (x,y) :: ls' => (x + y) + (listAdd ls') 

I think it makes no sense to take two separate lists. Just grab the list that contains the product ints. If you need to build this, you can call the zip function:

 fun zip xs ys : case xs, ys of [], [] => [] | xs, _ => [] | _, ys => [] | x::xs', y::ys' => (x,y) :: (zip xs' ys') 

In general, if you really wanted this, you can write a much more abstract function that has a common type:

 fun absProdList : ((`a * `b) -> `c) -> (`a * `b) list -> `c list 

This function is simple:

 fun absProdList f ls = case l of [] => [] | (x,y) :: ls' => (f (x,y)) :: (absProdList f ls') 

This function is a supertype of the addList function addList . Just define an anonymous function to recreate addList as:

 fun addList' ls = absProdList (fn (x,y) => x + y) ls 

As you can see, the definition of generic function types makes specific calls for functions that are a substitute for types for the general, much simpler and more elegant, with the appropriate combination: Currying, Higher-Order, and anonymous functions.

0
source

Source: https://habr.com/ru/post/1502098/


All Articles