DEV Community

hiclab
hiclab

Posted on • Edited on

Check if a list contains a value in RCPTT

This post will focus on how to iterate over a list to check whether it contains a given element.

Using each

The ECL command each is the one of most used commands in RCPTT. It is very useful because it makes the code clean, simple and much more readable in comparison with the command loop. However, we have to take into account that it doesn’t support breaks. That is, we are forced to go through all elements of the list even if it is not necessary, for example when we have found the target element before reaching the end of the list.

In the following example, we return a value if the list contains the specified element. Afterwards, we check whether the number of returned values is greater than 0 in order to return true or false.

proc itemExists [val items -input] [val targetItem] {
    $items | each [val it] {
        if [$it | eq $targetItem] {
            bool true
        }
    } | length | gt 0
}

Using loop

The command loop supports a kind of break using recur which is another command. Basically, we invoke recur to continue the execution of the loop. We are allowed to use variables and modify them when iterating.

proc itemExists [val items -input] [val targetItem] {
    loop [val index 0] [val max [$items | invoke elements | invoke size]] {
        if [$index | lt $max] {
            if [$items | get $index | not-eq $targetItem] {
                recur [$index | plus 1][$max]
            } -else {
                bool true
            }
        } -else {
            bool false
        }
    } | equals true
}

As you can see above, the code is too complex in comparison with the previous one and make sure that the list is not empty since it fails when running $items | invoke elements.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay