zsh-users
 help / color / mirror / code / Atom feed
* A way to apply function to each element of an array
@ 2019-08-29  0:49 Sebastian Gniazdowski
  2019-08-29  2:47 ` Sebastian Gniazdowski
  2019-08-29 10:46 ` Roman Perepelitsa
  0 siblings, 2 replies; 4+ messages in thread
From: Sebastian Gniazdowski @ 2019-08-29  0:49 UTC (permalink / raw)
  To: Zsh Users

Hello,
I thought that I share a method of applying of function to each
element of an array. I think that it's obvious for someone interested
in // substitution and (#m) and (#b) flags, but not necessarily for
others. Also, it would be much more beautiful if zsh would support
mksh's substitution ${|func;} which is replaced by the value that func
assigns to REPLY, assuming that func can take some arguments (i.e. the
$MATCH in the use case):

msfunc() { REPLY="${(Q)1} $RANDOM"; return 0; }
functions -Ms msfunc 1 1 msfunc
myarr=( value1 value2 abc1 abc2 )
myarr=( "${(@)${myarr[@]/(#m)*/$(( msfunc(${(q)MATCH}) ))$REPLY}/(#s)0/}" )
print -rl $myarr

Output:
value1 21720
value2 18920
abc1 3318
abc2 14483

The (#s) matches the start of the string and is just for to ensure
correctness and not actually needed. It however might save some time
when debugging code, when some 0s start to disappear from the strings
because of an specific, not always matching pattern (with (#b) flag,
for example). The 0 can be also changed to some random number in such
case.

-- 
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
blog: http://zdharma.org

^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2019-08-29 11:14 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2019-08-29  0:49 A way to apply function to each element of an array Sebastian Gniazdowski
2019-08-29  2:47 ` Sebastian Gniazdowski
2019-08-29 10:46 ` Roman Perepelitsa
2019-08-29 11:13   ` Sebastian Gniazdowski

Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/zsh/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).