JOIN, REJOIN, but what about ADJOIN?
JOIN is a useful REBOL function. However, sometimes it can get you into trouble. That's because JOIN and its brother, REJOIN, use their first argument as the datatype of the result. For instance, if the first argument is a file type, the result is a file type. This is true for all other string types: >> join "Example" 123 == "Example123" >> rejoin [%file 123] == %file123 >> join <tag > 123 == <tag 123> >> rejoin [http://www.rebol.com/ "index.html"] == http://www.rebol.com/index.html However, there are times when you want the result to be a string, not the datatype of the first value. It can really bite you in the hand, such as when the first value is a tag type: >> join <a href="page.html"> ["Page" </a>] == <a href="page.html"Page</a>> >> rejoin [<a href="page.html"> "Page" </a>] == <a href="page.html"Page</a>> To avoid this developers often add an empty string as the first argument: >> join "" [<a href="page.html"> "Page" </a>] == {<a href="page.html">Page</a>} >> rejoin ["" <a href="page.html"> "Page" </a>] == {<a href="page.html">Page</a>} This JOIN problem came about because a join is implied when whenever a block is appended. In other words, join is so common that it does not need to be explicitly specified. Here are examples: >> str: "Example: " == "Example: " >> append str [<a href="page.html"> "Page" </a>] == {Example: <a href="page.html">Page</a>} >> write %test.txt [<a href="page.html"> "Page" </a>] >> read %test.txt == {<a href="page.html">Page</a>} That is why the JOIN function has that datatype feature. So, how do you join and always make the result a string? Probably the most efficient form is: >> to-string [<a href="page.html"> "Page" </a>] == {<a href="page.html">Page</a>} If your block contains variables, you may need to add a REDUCE or a COMPOSE: >> to-string reduce [<a href="time.html"> now </a>] == {<a href="time.html">6-Jan-2005/17:40:21-8:00</a>} This is a useful REBOL idiom: to-string reduce block It is essentially a JOIN that always produces a string result. However, to be more frequently used, such an idiom needs to become a standard mezzanine function; hopefully, one with a short name. adjoin: func [block] [to-string reduce block] This is a suggestion, and it might be added to a future REBOL release. I use the word ADJOIN here because it has the word JOIN within it, and most new REBOL programmers are going to search first for that. Unfortunately, the word JOIN is already used and cannot be redefined. Other choices might be: ajoin, enjoin, or joins. Your comments are requested.
|
Updated 19-Nov-2024 - Copyright Carl Sassenrath - WWW.REBOL.COM - Edit - Blogger Source Code |