HardwareEng.
HardwareEng.

Reputation: 99

Retrieve selective items from list

Is there a way to get items from a list according to some function?

I know there is a way to get items by regular expression by using lsearch -regexp but It's not what I need.

Upvotes: 2

Views: 81

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

In Tcl 8.6, you can use the lmap command to do this by using continue to skip the items you don't want (or break to indicate that you've done enough processing):

set items {0 1 2 3 4 5 6 7 8 9 10}
set filtered [lmap i $items {if {$i==sqrt($i)**2} {set i} else continue}]
# Result: 0 1 4 9

This can be obviously extended into a procedure that takes a lambda term and a list.

proc filter {list lambda} {
    lmap i $list {
        if {[apply $lambda $i]} {
            set i
        } else {
            continue
        }
    }
}

set filtered [filter $items {i { expr {$i == sqrt($i)**2} }}]

It's possible to do something similar in Tcl 8.5 with foreach though you'll need to do more work yourself to build the list of result items with lappend

proc filter {list lambda} {
    set result {}
    foreach i $list {
        if {[apply $lambda $i]} {
            lappend result $i
        }
    }
    return $result
}

Usage is identical. (Tcl 8.4 and before — now unsupported — don't support the apply command.)

Upvotes: 2

Related Questions