tag:blogger.com,1999:blog-2874057012077056643.post3268407262264338334..comments2017-09-04T16:31:08.234-04:00Comments on renascencegirl: Comparison of Arrays, brieflyElli Lhttps://plus.google.com/101731641844161494644noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-2874057012077056643.post-58304294433413824822014-04-23T19:25:00.176-04:002014-04-23T19:25:00.176-04:00Gary- that's a neat way of looking at it. Than...Gary- that's a neat way of looking at it. Thank you for the nuggets!Elli Lhttps://www.blogger.com/profile/14339885013628227274noreply@blogger.comtag:blogger.com,1999:blog-2874057012077056643.post-90281021391067069252014-04-22T18:10:46.353-04:002014-04-22T18:10:46.353-04:00Hi Elli,
Really, both arrays and associative ar...Hi Elli,<br /><br /> Really, both arrays and associative arrays are just special cases of functions, whose values have been precomputed and stored for fast lookup. Allow me to explain.<br /><br /> Imagine you have two sets of values X and Y and a projection function that maps each value in X to a single value in Y. Now if X contains integer values, this matches the semantics of an array. If X contains non-integer values, this matches the semantics of an associative array.<br /><br /> To take the metaphor a bit further, imagine the values from your X and Y sets arranged along X and Y axes on a 2D plot. Mark the (X,Y) points corresponding to the entries in your array or associative array, and once again we have a clean mathematical representation of our data structures.<br /><br /> And what do both of these mathematical descriptions of arrays and associative arrays have in common? Yep, both of these show that those data structures could be represented perfectly well with deterministic functions taking one input and returning one output.<br /><br />Here's an example of an array-like function in the Clojure programming language (http://clojure.org):<br /><br />(defn my-array-function [index]<br /> (case index<br /> 0 "first value"<br /> 1 "second value"<br /> 2 "last value"<br /> (throw (Exception. "Index out of bounds."))))<br /><br />And here's an example of an associative array-like function:<br /><br />(defn my-associative-array-function [key]<br /> (case key<br /> "foo" "first value"<br /> "bar" "second value"<br /> "baz" "last value"<br /> nil))<br /><br />Easy peasy, right?<br /><br />So why would we want to use an array or associative array in our programs rather than just implementing the same effect with functions? Well...first, using a data structure provides a more declarative, readable representation of our information. Second, array and associative array lookup is quite fast, while function evaluation might be slow, depending on how the result is calculated.<br /><br />So there you go. Some nuggets of wisdom to chew on while sipping tea in the evening.<br /><br />Happy Hacking!<br /> ~GaryGary Johnsonhttps://www.blogger.com/profile/12593869933438257041noreply@blogger.com