Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could think about each function as a sequence of steps:</p> <blockquote> <p>by functions How can I duplicate every element of a list with itself twice.</p> </blockquote> <p>To duplicate each element of a list <em>xs</em>, you need to apply a function which, given an argument <em>x</em>, returns the list [<em>x</em>, <em>x</em>], to each element of the list; since this produces a list of lists, you will need to concatenates the results. The concatenated list is the list with each element duplicated:</p> <pre><code>k :: a -&gt; [a] k x = [x,x] g :: (a -&gt; b) -&gt; [a] -&gt; [b] g f [] = [] g f (x:xs) = f x : g f xs duplicate :: [a] -&gt; [a] duplicate = concat . (g k) </code></pre> <p>Since <code>g = map</code> and <code>concat . g = concatMap</code>, the function you are looking for is:</p> <pre><code>duplicate :: [a] -&gt; [a] duplicate = concatMap (\x -&gt; [x,x]) =&gt; concatMap (replicate 2) </code></pre> <p>To replace an element <em>a</em> by a value <em>b</em>, iterate over the list with a function which exchanges <em>b</em> for <em>a</em>:</p> <pre><code>f :: Eq a =&gt; a -&gt; a -&gt; a -&gt; a f o r x = if x == o then r else x replaceOn :: Eq a =&gt; a -&gt; a -&gt; [a] -&gt; [a] replaceOn o r [] = [] replaceOn o r (x:xs) = f o r x : h o r xs </code></pre> <p>Since <code>h = map f</code>, you have:</p> <pre><code>replaceOn :: a -&gt; a -&gt; [a] -&gt; [a] replaceOn o r = map (\x -&gt; if x == o then r else x) </code></pre> <p>I'm not a Haskell expert. However, it helps me to break Haskell problems into sequences of "returned values". These are like "steps" in an imperative language. The steps are composed using combinators, higher order functions, and ordering of functions. You can think about sequencing like: do <em>f</em> to get <em>x</em>; to <em>g</em> with <em>f x</em> to get <em>x'</em>, etc.</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. This table or related slice is empty.
    1. 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