Home > database >  Haskell make recursion for Chars in String
Haskell make recursion for Chars in String

Time:11-22

I want to create game Magic 15 Puzzle in Haskell I have function set :: [[Char]] -> Char -> [[Char]] . It switches Char with empty space in [[Char]].

*Main> pp puzzle2
AC DE
FBHIJ
KGLNO
PQMRS
UVWXT
*Main> pp (set puzzle2 'C')
A CDE
FBHIJ
KGLNO
PQMRS
UVWXT
*Main> 

Now I want to do recursion for [Char] (or String) like this (To do set xs for previous set x)

puzzle :: Result -> [Char] -> Result
puzzle gameboard (x:xs) =  set (set (x:xs) x) xs 

But compilation says it is error:

 Couldn't match expected typeChar’ with actual type ‘[Char]’

I expect this output:

*Main> pp(puzzle puzzle2 "CB")                    
ABCDE
F HIJ
KGLNO
PQMRS
UVWXT
      

What can I do to solve this? Thanks a lot in advance for answer!

Whole Code:

import Data.Char
type Result = [String]
pp :: Result -> IO ()
pp x = putStr (concat (map (  "\n") x))

puzzle2 :: [[Char]]
puzzle2 = ["AC DE",
           "FBHIJ",
           "KGLNO",
           "PQMRS",
           "UVWXT"]





getCords board x = head ( head [[(row_index, column_index) |(column_index, char) <- zip[1..] row, x == char] |(row_index,row)<- zip [1..]board,x `elem` row])
getRow board c = fst ( getCords board c)
getCol board c = snd ( getCords board c)
check ch1 ch2 board =  (getRow board ch2 == getRow board ch1   1 || getRow board ch2 == getRow board ch1 - 1) && (getCol board ch1 == getCol board ch2) || ((getRow board ch1 == getRow board ch2) && (getCol board ch2 == getCol board ch1   1 || getCol board ch2 == getCol board ch1 - 1) )





set gameboard x | check x ' ' gameboard = [[if ch == ' ' then x else if ch == x then ' ' else ch | ch<- line] | line<-gameboard]
                | not (check x ' ' gameboard ) = [[ch | ch<- line] | line<-gameboard]





puzzle :: Result -> [Char] -> Result
puzzle gameboard (x:xs) =  set (set (x:xs) x) xs 

CodePudding user response:

Just change the last function to

puzzle :: Result -> [Char] -> Result
puzzle g [] = g
puzzle g (x:xs) =  puzzle (set g x) xs 
  • Related