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:
- The
s1
and thep1
in thepuzz s1 p1
aren't your constantss1
andp1
. They are only templates. For examplepuzz [" B"] "B"
returns["BB "]
andp1
becomes[" B"]
ands1
becomes"B"
in that function call. - 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. - 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 bep
and tail will bep1
.
puzz s1 [] = s1
- When second parametr is empty list, then return first parameter (end).
puzz out p1
- Calling puzz for the changeds1
asout
andp1
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 "]