当前位置: 动力学知识库 > 问答 > 编程问答 >

Selectively iterating over a list in Scheme

问题描述:

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.

网友答案:

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))
分享给朋友:
您可能感兴趣的文章:
随机阅读: