if i.0 return 0

11 views
Skip to first unread message

Pascal Jasmin

unread,
Sep 4, 2025, 9:20:28 PMSep 4
to Forum
what is best way to test for "null" and if null return 0

f 3  NB. any non null at all, return y
3

f i.0
0

+/ works for scalars.

robert therriault

unread,
Sep 4, 2025, 10:55:28 PMSep 4
to fo...@jsoftware.com
Hey Pascal,

I would guess that there are more elegant ways to approach this, but this is what I came up with.


s1=: 0:`]@.(*@#) NB. test for no items
s2=: 0:`]@.(0 -.@e. $) NB. test for empty array

s1 i. 2 3
0 1 2
3 4 5
s2 i. 2 3
0 1 2
3 4 5
s1 i. 0
0
s2 i. 0
0
s1 3 0 $ 5 NB. returns arg if it has items



s2 3 0 $ 5 NB. returns 0 if array is empty
0

Cheers, bob
> To unsubscribe from this group and stop receiving emails from it, send an email to forum+un...@jsoftware.com.
>

Pascal Jasmin

unread,
Sep 4, 2025, 11:05:45 PMSep 4
to 'robert therriault' via forum
very nice.  s2 seems the most resilient.

for null or vector situations,

0 (0: :: {) y

can zero out any missing "expected" vector elements with x cycling through possibly expected vector indices.

bill lam

unread,
Sep 4, 2025, 11:13:51 PMSep 4
to fo...@jsoftware.com
this should work for both array and scalar
*/@$

Raul Miller

unread,
Sep 4, 2025, 11:20:17 PMSep 4
to fo...@jsoftware.com
I think by "null" you mean an array with an empty dimension?

If so, maybe

f=: {.~ 1 >. $

--
Raul

Henry Rich

unread,
Sep 4, 2025, 11:33:42 PMSep 4
to fo...@jsoftware.com
Good solutions, but if you're putting them into a library consider:

1. ^:v is very fast, much faster than @.v

2.
https://code.jsoftware.com/wiki/Vocabulary/SpecialCombinations#Whole-Array_Operations
gives the best forms to test for empty etc.

Using that you get

s1 =: 0:^:(0=#)
s2 =: 0:^:(0 e. $)

As you show, the spec is defective.  What does 'null' mean?  You give
answers for the 2 most plausible definitions.

Henry Rich

robert therriault

unread,
Sep 4, 2025, 11:39:18 PMSep 4
to fo...@jsoftware.com
I find your solutions more readable as well Henry. Simple "if true then 0 else original argument" construct.

Cheers, bob
Reply all
Reply to author
Forward
0 new messages