sharkdp / shell-functools

Functional programming tools for the shell
MIT License
1.2k stars 49 forks source link

Custom functions #38

Open RustemB opened 5 years ago

RustemB commented 5 years ago

How about custom functions support (or plugins) Like:

seq 5 | filter is_odd

will return:

1
3
5

where is_odd is custom function (e.g. in ~/.config/shell-functools/plugins/main.py directory)

@functools.func("Int", "Bool") #or @functools.func(int, bool)
def is_odd(a: int) -> bool:
    return a % 2 == 1

but, yes, it looks very complicated...

sharkdp commented 5 years ago

Interesting idea, thank you!

jdhedden commented 2 years ago

Offering

For README.md:

Usage of condition

The condition function permits filtering using a definition string to Python's lambda function.

> seq -3 3 | filter condition 'x : x>0'
1
2
3

> seq -5 5 | filter condition 'x : x%3 == 0 or x == 1'
-3
0
1
3

> echo -e '1\t2\n3\t2\n1\t1' | filter cond 'x,y: x>y'
3   2

For ft/ft/functions.py:

@register("cond", "condition")
@typed(None, T_BOOL)
def condition(definition, inp):
    _lambda = 'lambda ' + definition.value
    if type(inp) == list:
        args = list(map(lambda v: v.value, inp))
        return (eval(_lambda))(*args)
    else:
        return (eval(_lambda))(inp)
sharkdp commented 2 years ago

Great idea. Note that I'm not using this project myself anymore, so I'm not really actively maintaining it. I'd be happy to merge a PR with proper tests though.