Haskell 将字符串转换为二进制列表

Haskell 将字符串转换为二进制列表,haskell,Haskell,我开始学习haskell,我需要你的帮助,有些事情可能很简单,但我无法解决 我有一个字符串: ABCDEFG 我需要将此字符串转换为以下格式: A-B B-C C-D D-E E-F F-G 有人能给我一些建议吗? 谢谢。只需从数据中使用zip即可。如下所示: let str = "ABCDEFG" in zip str $ tail str main :: IO () main = do let str = "ABCDEFGH" couples = zip str

我开始学习haskell,我需要你的帮助,有些事情可能很简单,但我无法解决

我有一个字符串:

ABCDEFG
我需要将此字符串转换为以下格式:

A-B
B-C
C-D
D-E
E-F
F-G
有人能给我一些建议吗? 谢谢。

只需从数据中使用zip即可。如下所示:

let str = "ABCDEFG"
in zip str $ tail str
main :: IO ()
main = do
  let str     = "ABCDEFGH"
      couples = zip str $ tail str
  mapM_ (\(x,y) -> putStrLn $ x : '-' : y : "") couples 
它返回成对的列表[Char,Char]

然后,要输出问题中类似的内容,可以执行以下操作:

let str = "ABCDEFG"
in zip str $ tail str
main :: IO ()
main = do
  let str     = "ABCDEFGH"
      couples = zip str $ tail str
  mapM_ (\(x,y) -> putStrLn $ x : '-' : y : "") couples 
只需使用来自数据的zip。如下所示:

let str = "ABCDEFG"
in zip str $ tail str
main :: IO ()
main = do
  let str     = "ABCDEFGH"
      couples = zip str $ tail str
  mapM_ (\(x,y) -> putStrLn $ x : '-' : y : "") couples 
它返回成对的列表[Char,Char]

然后,要输出问题中类似的内容,可以执行以下操作:

let str = "ABCDEFG"
in zip str $ tail str
main :: IO ()
main = do
  let str     = "ABCDEFGH"
      couples = zip str $ tail str
  mapM_ (\(x,y) -> putStrLn $ x : '-' : y : "") couples 

您可以使用zip和drop将连续字符配对:

然后可以映射字符对列表以创建字符串:

map (\(f, s) -> f:'-':s:[]) pairs
这将为您提供一个字符串列表

正如评论所指出的,您可以使用zipWith和tail,而不是zip、map和drop 1:

您可以在一行中执行此操作:

let stringList = map (\(f, s) -> f:'-':s:[]) $ zip str (drop 1 str)
如果您需要单个输出字符串,可以使用unlines,例如

作为单一功能:

formatPairs :: String -> String
formatPairs str = unlines $ map (\(f, s) -> f:'-':s:[]) $ zip str (drop 1 str)

如果需要打印,可以使用putStr:


您可以使用zip和drop将连续字符配对:

然后可以映射字符对列表以创建字符串:

map (\(f, s) -> f:'-':s:[]) pairs
这将为您提供一个字符串列表

正如评论所指出的,您可以使用zipWith和tail,而不是zip、map和drop 1:

您可以在一行中执行此操作:

let stringList = map (\(f, s) -> f:'-':s:[]) $ zip str (drop 1 str)
如果您需要单个输出字符串,可以使用unlines,例如

作为单一功能:

formatPairs :: String -> String
formatPairs str = unlines $ map (\(f, s) -> f:'-':s:[]) $ zip str (drop 1 str)

如果需要打印,可以使用putStr:


…可以进一步压缩到zipWithM\ux y->putStrLn$[x',-',y]str tail str。这对我来说真是奇怪的代码,但是。。。哇:我得学习这个函数。谢谢…它可以进一步压缩到zipWithM\ux y->putStrLn$[x',-',y]str tail str。这对我来说真的很奇怪,但是。。。哇:我得学习这个函数。谢谢