Skip to content

Commit

Permalink
Implemented a quick sequence value replacement function.
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob414 committed Mar 4, 2021
1 parent 6ac6ea6 commit 5c2cc40
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
18 changes: 18 additions & 0 deletions kingston/lang.py
Expand Up @@ -95,6 +95,24 @@ def num_or_else(cand: Any) -> numbers.Number:
return cand


def replace(reps: dict, seq: Sequence) -> Sequence:
"""Simple replacement of values in a sequence. Returns a copy of
``seq`` where all values in ``seq`` that are equal to keys in
``reps`` are replaced by the values in ``reps`` corresponding to
that same key.
>>> replace({1:10, 3:30}, (1, 2, 3, 4, 5))
(10, 2, 30, 4, 5)
The return type is the same as of the parameter ``seq``::
>>> replace({1:10, 5:50}, [1, 2, 3, 4, 5])
[10, 2, 3, 4, 50]
"""
return fy.empty(seq).__class__(
map(lambda x: x in reps and reps[x] or x, seq))


def detect_numbers(seq: Iterable) -> Iterable:
return [num_or_else(el) for el in seq]

Expand Down
5 changes: 5 additions & 0 deletions kingston/test/test_lang.py
Expand Up @@ -204,3 +204,8 @@ class FromPrim(int):
pass

assert lang.primbases(FromPrim) == [int]

@fixture.doctest(lang.replace)
def test_replace(doctest):
res = doctest()
assert res == '', res

0 comments on commit 5c2cc40

Please sign in to comment.