0
votes

I have a list of objects in Scheme. Each object in turn is a list itself. I am using the map function to iterate over all the elements of the list and apply a function to them. However, I want to apply that function only if the element of the list satisfies some criteria. In C++ that would be something like this:

for(i=0; i<=n; i++)
{
    if(criteria(list[n]))
    //do something
}

How do I do this in Scheme? Right now, I am using the map function like this:

(map create-evaluation-link parse)

Where create-evaluation-link is a function and parse is the list.

1
Using for loops is often an indicator of imperative-style code. There may be a way to do things more functionally depending on what you're attempting to do. That said, Racket has for loops and list comprehensions, though that's obviously a different dialect. - Alexis King
When you say you want to apply that function only to lists satisfying some criterion, are you using map for its side-effects or its value? I'm wondering if you want to preserve the value of the non-matching lists in the the returned list, or if you are just running all of this for its side-effect. For example, if your criteria is (lambda (l) (even? (length l))), your input list is ((3 2 1) (2 1) (4 3 2 1)), do you want to be able to pass a function like car and get (2 4) as the result, or ((3 2 1) 2 4), or pass a procedure which has some side effect and gets run on the latter two? - Brian Campbell
I am using map for its value, not for the side effect. I just want to apply create-evaluation-link to the elements. Nothing more. In your example, I would want to apply my function only to (2 1) and (4 3 2 1). - Rohit Shinde

1 Answers

2
votes

With the approach you're taking, just map a function that checks whether the item meets the criteria:

(map (lambda (x)
       (if (criteria? x)
           (create-evaluation-link x)))
      parse)

However, as others have noted in the comments, using map to do imperative work may be a place where some other approach might be more natural in Scheme. For instance, you might first filter out the values that don't meet the criteria, and then map create-evaluation-link over that to get a list of evaluation-links.

(map create-evaluation-link (filter criteria? parse))