Singly-linked list/Element removal: Difference between revisions
Singly-linked list/Element removal (view source)
Revision as of 09:00, 12 September 2021
, 2 years ago→{{header|jq}}
Line 491:
After removing burritos:
<nil>
</pre>
=={{header|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq'''
For context see [[Singly-linked_list/Element_definition#jq]].
Here we define three filters for removing items from a SLL.
The functions which are defined recursively have an inner function
to take advantage of jq's tail-call optimization (TCO).
<lang jq># Input: a JSON object representing a SLL
# Output: an object with the same value after
# removal of the first item for which (.item|f) is truthy
def remove(f):
def r:
if has("item") and (.item|f) then .next
elif .next then .next |= r
else .
end;
r;
# Input: a JSON entity representing a SLL.
# Output: an object with the same value after
# removal of the first occurrence of $x if any.
def remove_item($x):
remove(. == $x);
def remove_all(f):
def r:
if has("item") and (.item|f) then .next | r
elif .next then .next |= r
else .
end;
r;</lang>
'''Example'''
<lang jq>{
"item": 1,
"next": {
"item": 2,
"next": null
}
}
| remove_all(. == 1)</lang>
{{out}}
<pre>
{
"item": 2,
"next": null
}
</pre>
|