【问题标题】:Haskell make recursion for Chars in StringHaskell 对字符串中的字符进行递归
【发布时间】:2021-12-31 10:44:03
【问题描述】:

我想在 Haskell 中创建游戏 Magic 15 Puzzle 我有函数 set :: [[Char]] -> Char -> [[Char]] 。 它用 [[Char]] 中的空格切换 Char。

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

现在我想像这样对[Char](或String)进行递归(为以前的set x 做set xs)

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

但是编译说是错误的:

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

我期望这个输出:

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

我能做些什么来解决这个问题?非常感谢您的回答!

完整代码:

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 

【问题讨论】:

    标签: haskell recursion


    【解决方案1】:

    把最后一个函数改成

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

    【讨论】:

    • 非常感谢,它有效,puzzle g [] = g 是什么意思?
    • 这意味着对于空字符串它不会改变,是吗?
    • 是的,就是递归结束的条件。
    猜你喜欢
    • 2018-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 2011-08-22
    • 2022-12-09
    • 1970-01-01
    • 2017-04-24
    • 2016-10-02
    相关资源
    最近更新 更多