Home > Enterprise >  How use result again in this case
How use result again in this case

Time:11-19

I am new to Haskell , I get result for first iterate. How save this result and again use with next parameter from char array p1 ? Entry in s1 is like a puzzle array, in p1 moves to empty, After making movements we have new puzzle array. First iterate ["A CDE","FBHIJ","KGLNO","PQMRS","UVWXT"] result is ["ABCDE", "FGHIJ", "KLMNO", "PQRST ", "UVWX "]

s1 = ["AC DE","FBHIJ","KGLNO","PQMRS","UVWXT"]

p1 = "CBGLMRST"

puzz :: Result -> [Char]-> Result
puzz s1 p1 =  let i = 0
                   p = p1 !! i
                   change r = [ if c == ' ' then p else if c == p then ' ' else c | c <- r ]
                   out = [ change r | r <- s1  ]
                in out 

CodePudding user response:

  1. The s1 and the p1 in the puzz s1 p1 aren't your constants s1 and p1. They are only templates. For example puzz [" B"] "B" returns ["BB "] and p1 becomes [" B"] and s1 becomes "B" in that function call.
  2. Don't try iterate (I removed part of code with the i). Use recursion. There are no variables in Haskell, only constants and input parameters. Input parameter (represented by the template) should be in each call different (closer to the end) because of referential integrity.
  3. Don't forget to finish the algorithm.

(p:p1) - Template of input parameter which says that there is a nonempty list and the first character will be p and tail will be p1.
puzz s1 [] = s1 - When second parametr is empty list, then return first parameter (end).
puzz out p1 - Calling puzz for the changed s1 as out and p1 from (p:p1) (recursion).

s1 = ["AC DE","FBHIJ","KGLNO","PQMRS","UVWXT"]

p1 = "CBGLMRST"

puzz :: [String] -> [Char]-> [String]
puzz s1 (p:p1) =  let                  
                  change r = [ if c == ' ' then p else if c == p then ' ' else c | c <- r ]
                  out = [ change r | r <- s1  ]
                in puzz out p1
puzz s1 [] = s1

Output:

   puzz s1 p1
=> ["ABCDE","FGHIJ","KLMNO","PQRST","UVWX "]
  • Related