Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing map to replace elements of a list with (x-y)*(x-y), where y is the initial element
    primarykey
    data
    text
    <p>I have a bit of homework to do and I am a complete newbie to Haskell. The question I am having trouble with is to write a function which when given an integer <code>x</code> and a list of integers apply <code>(x-y)*(x-y)</code> to each element in the list and output the new list, with <code>y</code> being each element of the input list.</p> <p>I have a very rough idea I will have to use the <code>map</code> function but I'm unsure how to go about it. </p> <p>I have been looking at examples for squaring each element in a list and kind of understand how that works, but how I would implement the <code>(x-y)*(x-y)</code> with <code>y</code> being the current element completely baffles me. </p> <pre><code>squares :: [Int] -&gt; [Int] squares (x:xs) = x * x : squares xs squares [] = [] </code></pre> <p>the exact question I have been set is, </p> <blockquote> <p>Write a function <code>rela</code> which takes as arguments an integer <code>x</code> and a list of integers. It returns a similar list, but where each element <code>y</code> has been replaced by <code>(x-y)*(x-y)</code>, e.g.</p> <pre><code>Main&gt; rela 2 [3,5,7] [1,9,25] </code></pre> </blockquote> <hr> <p>I have managed to get it working after reading through some books, but the code I have made misses out the first element in the list. Any explanation why?</p> <pre><code>equation1 :: Int -&gt; Int -&gt; Int equation1 x y = (x-y)*(x-y) rela :: Int -&gt; [Int] -&gt; [Int] rela x [] =[] rela x (y:ys) = [ equation1 x y | y &lt;- ys ] </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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