Group Abstract Group Abstract

Message Boards Message Boards

1
|
11.6K Views
|
12 Replies
|
9 Total Likes
View groups...
Share
Share this post:

Avoid unexpected behavior with ValueQ?

12 Replies

Sander Huisman, Tanks, this is also a good implementation. I tend to think that pure functions are the fastest way to proceed when writing algorithms... but that is more than a feeling than anything else.

It will keep in mind this alternative way of working things out.

Thanks again

Jesus

As a side note: you could use an association to store your data:

Associations provide generalizations of symbolically indexed lists, associative arrays, dictionaries, hashmaps, structs, and a variety of other powerful data structures.

Then when you ask for a value that is not yet defined it will return missing:

hash = <||>;
Do[AssociateTo[hash, i -> i], {i, 1, 10, 2}]
Table[If[MissingQ[hash[i]], "No value", hash[i]], {i, 10}]

returns the correct result. This might even be a faster and more flexible solution.

POSTED BY: Sander Huisman

Excellent - many thanks, Sander!

(As an off topic remark concerning readability: See this discussion).

Posted 9 years ago
POSTED BY: Itai Seggev

Thanks Guys

Your answers are all useful. Itai-- Thanks for your very precise explanation. It is educational. I am going to adopt 'map with a pure function' since it seems to me that it is more straightforward and easier to read.

Regards

Jesus

POSTED BY: Sander Huisman

I noticed the same thing--either way, it is a bug.

Moderators, please take note and pass on to the developers.

POSTED BY: David Reiss
POSTED BY: Szabolcs Horvát

Hi Jesus,

This is indeed some 'unexpected' behavior, as an alternative you can use (2 methods):

If[ValueQ[f[#]], f[#], "No value"] & /@ Range[10]
Table[If[Head[f[i]] =!= f, f[i], "No value"], {i, 10}]

I think it has to do with ValueQ[f[i]] that is converted to:

!Hold[Evaluate[f[i]]]===Hold[f[i]]

I think the Hold interferes with Table, but I'm not 100% sure what the exact problem is. Reading a 'trace' is never easy:

Trace[Table[If[ValueQ[f[i]], f[i], "No value"], {i, 2}]]

gives:

{Table[If[ValueQ[f[i]],f[i],No value],{i,2}],{{ValueQ[f[i]],!Hold[Evaluate[f[i]]]===Hold[f[i]],{{{{i,1},f[1],1},Hold[1]},Hold[1]===Hold[f[i]],False},!False,True},If[True,f[i],No value],f[i],{i,1},f[1],1},{{ValueQ[f[i]],!Hold[Evaluate[f[i]]]===Hold[f[i]],{{{{i,2},f[2]},Hold[f[2]]},Hold[f[2]]===Hold[f[i]],False},!False,True},If[True,f[i],No value],f[i],{i,2},f[2]},{1,f[2]}}
POSTED BY: Sander Huisman
POSTED BY: Henrik Schachner

That's a real neat tip! Thanks! A small improvement is to color the frames differently:

Framed[#, FrameStyle -> RandomColor[]] & //@

Thanks Henrik!

POSTED BY: Sander Huisman

Excellent - many thanks, Sander!

(As an off topic remark concerning readability: See this discussion).

POSTED BY: Henrik Schachner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard