Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array reduction #532

Open
igitur opened this issue Feb 12, 2024 · 4 comments
Open

Array reduction #532

igitur opened this issue Feb 12, 2024 · 4 comments
Labels

Comments

@igitur
Copy link
Contributor

igitur commented Feb 12, 2024

Hi,

I'm looking for a way to reduce arrays, e.g. I was hoping for something like this:

total_length = ["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | array.each @string.size | array.reduce @math.plus

Or in the case of summing, just

total_length = ["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | array.each @string.size | math.plus

But I can't find an obvious way. Is array reduction missing?

@igitur
Copy link
Contributor Author

igitur commented Feb 12, 2024

I even tried this:

total = 0
{{ ["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | array.each @string.size | array.each @(do; total = total  + $0; ret total; end) | array.last }}

This actually works, but yields a weird answer of 138.

@xoofx
Copy link
Member

xoofx commented Feb 13, 2024

Yeah, there is nothing builtin. Easiest might be to create your own C# function or you can try to define a Scriban function like this:

func reduce(a0, f0); $total = null; for $x in a0; if $total == null; $total = f0($x); else; $total += f0($x); end; end; ret $total; end;

total_length = ["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | reduce(@array.size)

@xoofx xoofx added the question label Feb 13, 2024
@igitur
Copy link
Contributor Author

igitur commented Feb 13, 2024

@xoofx Ah, great thanks.

I used that as base and came up with a more generic reduce function:

{{ 
func reduce(a0, f0); $result= null; for $x in a0; if $result== null; $result = $x; else; $result= $result | f0 $x; end; end; ret $result; end;

["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | array.each @string.size | reduce(@math.plus)
}}

Or with custom function:

{{ 
func reduce(a0, f0); $result= null; for $x in a0; if $result== null; $result = $x; else; $result= $result | f0 $x; end; end; ret $result; end;

product(x,y) = x * y

["Apple", "Banana", "Computer", "Mobile Phone", "Orange", "Sofa", "Table"] | array.each @string.size | reduce(@product)
}}

@igitur
Copy link
Contributor Author

igitur commented Feb 14, 2024

An official array.reduce function would be really useful though. I'll try my hand at a PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants