I tried for example
Thread[FileDate[FileNames["new*", "h:\\temp\\", 1]]]
It gives
FileDate::fstr: File specification {h:\temp\NEWEA7D.tmp,h:\temp\NEWEA7E.tmp,h:\temp\NEWEAAE.tmp} is not a string of one or more characters. >>
but still gives the right answer
Out[13]= {{2013, 11, 18, 23, 14, 32.}, {2013, 11, 18, 23, 14,
32.}, {2013, 11, 18, 23, 14, 32.}}
Why is there a error message? How to avoid it?
Answer
This is a consequence of the semantics of Thread, which does not hold its arguments. This issue has been discussed many times in various Mathematica - related resources. For the case at hand, and also generally, there are several ways to avoid this issue.
The simplest solution would be to just avoid Thread here and use Map instead:
Map[FileDate, FileNames["*.nb", {"~/Documents"}, 1]]
If you insist on using Thread, then, basically, we want to prevent FileDate from evaluating before it gets appropriately threaded. In this case, this is made more complicated because we should still evaluate the inner code. One way to do this is this (I am using a slightly different code as an example):
With[{fnames = FileNames["*.nb", {"~/Documents"}, 1]},
Thread[Unevaluated[FileDate[fnames]]]
]
in this case, we use With to inject the piece of evaluated code, and Unevaluated to prevent FileDate from evaluating before it is threaded.
One other way to do this is to use the Block trick, to make FileDate temporarily inert:
Block[{FileDate}, Thread[FileDate[FileNames["*.nb", {"~/Documents"}, 1]]]]
There are other ways to resolve this, of course.
Comments
Post a Comment