Singly-linked list/Element removal: Difference between revisions
Content added Content deleted
Line 491: | Line 491: | ||
After removing burritos: |
After removing burritos: |
||
<nil> |
<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> |
</pre> |
||