我是haskell的新手,我目前正在网格游戏中编写单词搜索,可以在对角线,行和列中找到单词。我使用Data.List.transpose
来创建列,但输出总是创建新的空字符串。我尝试了过滤功能,但它没有改变输出:filter (not.null) (L.transpose y)
。输出如下所示:["IYYPPOLFHTNMTDI"," ","UTVCGNVAEEZXEIR"," ","PDCPLTRUGSWTSQC"," ","GZEGUDGHSZTGSDT"," ","RMCEDJABPEUERTL"," ","ATTRVRXGKBRAMRA"," ","DZISDRASHAODEOP"," ","EVWWUWIXWBHGMMT"," ","ENAGCDYTYIOAOTO"," ","PRLCFFFEPDIVRKP"," ","EXZRNOKLOKPLYSO"," ","QSRESYZICYKUOLX"]
初始网格:
grid :: [String]
grid
= ["I U P G R A D E E P E Q",
"Y T D Z M T Z V N R X S",
"Y V C E C T I W A L Z R",
"P C P G E R S W G C R E",
"P G L U D V D U C F N S",
"O N T D J R R W D F O Y",
"L V R G A X A I Y F K Z",
"F A U H B G S X T E L I",
"H E G S P K H W Y P O C",
"T E S Z E B A B I D K Y",
"N Z W T U R O H O I P K",
"M X T G E A D G A V L U",
"T E S S R M E M O R Y O",
"D I Q D T R O M T K S L",
"I R C T L A P T O P O X" ]
如何解决此问题或是否有更好的方法来转置字符串列表?
答案 0 :(得分:3)
问题在于transpose
将字符串视为字符列表,包括空格。如果你尝试过:
transpose ["ABC",
"DE ",
"FGH"]
你得到:
["ADF",
"BEG",
"C H"]
你可以看到包含的所有字符,空格都是转置的。
对于您的特定情况,可以轻松解决问题。您可以使用words
和unwords
将"A B C"
转换为["A","B","C"]
,然后在转置前后转换回来:
> import Data.List
> (map unwords . transpose . map words) ["A B C","D E F","G H I"]
["A D G","B E H","C F I"]
>
filter
无法正常工作的原因是只有空字符串null
- 一串空格非空。你可以使用:
> import Data.Char
> filter (not . all isSpace) ["abc"," ","def"]
["abc","def"]
>
作为旁注,您可能需要重新考虑是否要在程序内部用空格表示网格。看起来使用它们会更容易:
[["a","b","c"],["d","e","f"],["g","h","i"]] :: [[String]]
或:
["abc","def","ghi"] :: [[Char]]
内部,只在输入或输出网格时添加或减去空格。
对于前一种表示形式,您可以使用map words
和map unwords
来回转换。对于后者,您可以使用:
> map (intersperse ' ') ["abc","def","ghi"]
["a b c","d e f","g h i"]
> map (concat . words) ["a b c","d e f","g h i"]
["abc","def","ghi"]
>