Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>This may seem quite stupid but how do I access elements in a List ?</p> </blockquote> <pre><code>(nth coll index) </code></pre> <p>For example:</p> <pre><code>(nth [1 2 3 4] 2) ; -&gt; 3 (since it uses zero-based indexing) </code></pre> <blockquote> <p>Is there a way to create a class "entry" that would contain "name" "adress" "phone number" variables ? or is that impossible in clojure (and functional programming in general ?) If I can't have a List of objects containing that information, how would I go about this task ?</p> </blockquote> <p>It's possible in Clojure, but unidiomatic. In Clojure, the basic abstraction for data entities are maps, not classes (except for some corner cases where direct interoperation with Java frameworks is needed). So you would just use a map:</p> <pre><code>(def entry {:name "x" :address "y" :phone-number "z"}) </code></pre> <p>To access the item's name, you either use</p> <pre><code>(:name entry) </code></pre> <p>or</p> <pre><code>(get entry :name) </code></pre> <p>The former works only when the keys of the map are keywords, the latter works with all types of key.</p> <p>So for your example, your data model (the phonebook) would be a seq (say, a list or a vector) of such maps.</p> <blockquote> <p>I was thinking of having a function that reads user input to know what the user wants to do (add entry, delete entry or print info) then calls the appropriate function to do that which calls back the first function when it's done. Is passing as a parameter the List of entries to each function the right thing to do?</p> </blockquote> <p>Since your model consists of only one main data structure (the phone book seq), passing it as an arg is certainly an appropriate way to design your functions. If you expect to have more kinds of top-level containers (i.e. for a more real world application), I'd recommend looking into the <a href="http://groups.google.com/group/clojure/browse_thread/thread/cd88c3d948ff6b4a" rel="noreferrer">Application Context Pattern</a>, which will look a bit intimidating at first (at least it did for me, and it contains a lot of Clojure-specific jargon), but is well worth the effort to learn.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload