Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You're confusing mutability with data structure. It <em>is</em> a proper list — just not one you're allowed to modify. Haskell is purely functional, meaning values are constant — you can't change an item in a list any more than you could turn the number 2 into 3. Instead, you perform calculations to create new values with the changes you desire.</p> <p>You could define that function most simply this way:</p> <pre><code>add ls idx el = take idx ls ++ el : drop idx ls </code></pre> <p>The list <code>el : drop idx ls</code> reuses the tail of the original list, so you only have to generate a new list up to <code>idx</code> (which is what the <code>take</code> function does). If you want to do it using explicit recursion, you could define it like so:</p> <pre><code>add ls 0 el = el : ls add (x:xs) idx el | idx &lt; 0 = error "Negative index for add" | otherwise = x : add xs (idx - 1) el add [] _ el = [el] </code></pre> <p>This reuses the tail of the list in the same way (that's the <code>el : ls</code> in the first case).</p> <p>Since you seem to be having trouble seeing how this is a linked list, let's be clear about what a linked list is: It's a data structure consisting of cells, where each cell has a value and a reference to the next item. In C, it might be defined as:</p> <pre><code>struct ListCell { void *value; /* This is the head */ struct ListCell *next; /* This is the tail */ } </code></pre> <p>In Lisp, it's defined as <code>(head . tail)</code>, where <code>head</code> is the value and <code>tail</code> is the reference to the next item.</p> <p>In Haskell, it's defined as <code>data [] a = [] | a : [a]</code>, where <code>a</code> is the value and <code>[a]</code> is the reference to the next item.</p> <p>As you can see, these data structures are all equivalent. The only difference is that in C and Lisp, which are not purely functional, the head and tail values are things you can change. In Haskell, you can't change them.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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