gpt4 book ai didi

haskell - 如何反转字符串中的字符并将数字保留在原始索引处?

转载 作者:行者123 更新时间:2023-12-02 16:56:08 25 4
gpt4 key购买 nike

我最近开始学习Haskell。我正在尝试反转包含字符和数字的字符串。该字符串将被反转,将数字保留在原始位置。

Original String = "H1AW2J1"

Reversed = J1WA2H1

我正在尝试遵循我在 Swift 中使用的模式。

  1. 过滤数字,然后反转字符串。
  2. 查找原始字符串中的数字索引。
  3. 将第 2 步中获得的索引处的数字插入到第 1 步中的字符串中。

下面是执行上述步骤的代码。

reversedChars“H1AW2J1”重新调整“JWAH”

reversedChars  = reverse . filter isLetter

索引返回元组。

indexes xs = [(x, elemIndex x xs) | x <- xs]

[('H',Just 0),('1',Just 1),('A',Just 2),('W',Just 3),('2',Just 4),('J',Just 5),('1',Just 1)]

问题

  1. 如何将相应索引处的数字插入到 reversedChars
  2. elemIndex 对于多次出现的 1,返回相同的索引 Just 1

最佳答案

  1. How to insert digits at the repective index into reversedChars

我会使用这样的递归函数,如果遇到字母,它会插入下一个反向字符,否则只插入实际字符:

import Data.Char

reverseLetters :: String -> String
reverseLetters xs = go xs (reverse $ filter isLetter $ xs)
where
go xs [] = xs
go (x:xs) (r:rs) | isLetter x = r : go xs rs
| otherwise = x : go xs (r:rs)

main = print $ reverseLetters "H1AW2J1"

输出:

"J1WA2H1"
  1. elemIndex is returning same index Just 1 for multiple occurrence of 1.

那是因为这就是 elemIndex 定义要返回的内容。如果您想要所有索引,您可以这样做:

Prelude> map fst $ filter ((== '1') . snd) $ zip [0..] "H1AW2J1"
[1,6]

关于haskell - 如何反转字符串中的字符并将数字保留在原始索引处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com