From the course: Programming Foundations: Discrete Mathematics

Unlock the full course today

Join today to access over 22,700 courses taught by industry experts or purchase this course individually.

Perform functions on lists

Perform functions on lists

From the course: Programming Foundations: Discrete Mathematics

Start my 1-month free trial

Perform functions on lists

- [Voiceover] Ok, now that we've seen how to create lists in SML, let's take a look at how to perform functions on lists. To do this, we're going to need to write our own new functions. Let's start by writing a function that finds the sum of all the items in a list. Here, I have a short list with some prime numbers. Let's write a function that will add all the numbers. I need to start by typing in "fun" to tell the interpreter i'm creating a new function. We'll call it "sum". Now in parentheses, I need to tell the interpreter what to expect. So i'm going to put two square brackets, open and closed, so that it knows to expect a list. I close my parentheses and now i have to give it a default value in case the user does not provide any elements in the list. In that case, I want the function just to return a zero. Ok we took care of that base case there. Now, I want to create a recursive process that will go through all the elements in the list. So i'm going to call "sum" again. I give a…

Contents