title: Haskell: Change the (n,m)th element in a Lists in List
body: <p>The <code>replaceAtMatrix</code> function should take in a tuple <code>(Int,Int)</code> that decides what position is the value that needs to be changed, <code>a</code> value to be changed to, and the List in List <code>[[a]]</code>.</p>
  <p>If the tuple's values exceed the lists length the original <code>[[a]]</code> needs to be returned.</p>
  <pre><code>replaceAtList :: Int -&gt; a -&gt; [a] -&gt; [a] 
  replaceAtList _ _ [] = []
  replaceAtList 0 a (_:xs) = a:xs
  replaceAtList number a (x:xs)
      | number &lt; 0 = x:xs
      | number &gt; (length (x:xs)-1) = x:xs 
      | otherwise = x : replaceAtList (number-1) a xs
  
  replaceAtMatrix :: (Int,Int) -&gt; a -&gt; [[a]] -&gt; [[a]]
  replaceAtMatrix _ _ [] = []
  replaceAtMatrix (0,num2) a (x:xs) = replaceAtList num2 a x : xs
  replaceAtMatrix (num1,num2) a (x:xs)
      | num1 &lt; 0 = x:xs
      | num1 &gt; (length (x:xs)-1) = x:xs
      | num2 &lt; 0 = x:xs
      | num2 &gt; (length (x:xs)-1) = x:xs 
      | otherwise = x : replaceAtMatrix (num1-1,num2) a xs
  </code></pre>
  <p>There are test for which I checked, and it passes most of them, but there's one where it goes in an infinite cycle. Here's the tests that work.</p>
  <pre><code>replaceAtMatrix (-1,0) 'A' [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;] == [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;]
  replaceAtMatrix (0,0) 'A' [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;] == [&quot;Acd&quot;,&quot;lds&quot;,&quot;rtz&quot;]
  replaceAtMatrix (2,0) 'A' [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;] == [&quot;bcd&quot;,&quot;lds&quot;,&quot;Atz&quot;]
  replaceAtMatrix (3,0) 'A' [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;] == [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;]
  replaceAtMatrix (2,2) 'A' [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtz&quot;] == [&quot;bcd&quot;,&quot;lds&quot;,&quot;rtA&quot;]
  </code></pre>
  <p>And here's the one that doesn't.</p>
  <p>Edit: I just realized it's probaly beacuse I use length on an infinite list. How can I rewrite it without using length?</p>
  <pre><code>take 5 (replaceAtMatrix (1,2) 100 [[1..],[1,11..],[],[12,13,14]] !! 1) == [1,11,100,31,41]
  </code></pre>
  <p>Without the guard, I get a variable not in scope error.</p>
  <pre><code>replaceAtList :: Int -&gt; a -&gt; [a] -&gt; [a] 
  replaceAtList _ _ [] = []
  replaceAtList 0 a (_:xs) = a:xs
  replaceAtList number a (x:xs) = x : replaceAtList (number-1) a xs
  
  replaceAtMatrix :: (Int,Int) -&gt; a -&gt; [[a]] -&gt; [[a]]
  replaceAtMatrix _ _ [] = []
  replaceAtMatrix (0,num2) a (x:xs) = replaceAtList num2 a x : xs
  replaceAtMatrix (num1,num2) a (x:xs) = x : replaceAtMatrix (num1-1,num2) a xs
  </code></pre>