【问题标题】:Moving the first element of a string to the last element of the preceding string using haskell使用haskell将字符串的第一个元素移动到前一个字符串的最后一个元素
【发布时间】:2023-03-14 10:18:01
【问题描述】:

这几天一直在尝试解决这个问题。例如:

k ["abc","def","ghi"] = ["bcd","efg","hia"]
k ["once","upon","a","time"] = ["nceu","pona","t","imeo"]

我正在尝试使用递归创建一个函数,而另一个则不这样做。这是我得到的最接近的:\

k [] = []
k [[]] =[[]]
k [_:_] = [_:_]
k (x:xs:xss) = ([i x xs]  ++ [i xs (last (x:xs:xss))]  ++ [i (last (x:xs:xss)) x ]) : k [x]
> k ["once","upon","a","time"]
[["nceu","pont","imeo"]]

任何提示表示赞赏:)

编辑:忘记包含之前创建的函数

i :: [a] -> [a] -> [a]
i [] y = y
i x [] = x
i x y = tail x ++ [head y]

【问题讨论】:

  • 你能写一个更简单的函数来旋转单个元素rotate :: [a] -> [a],例如rotate "abcd" = "bcda"rotate "once upon a time" = "nce upon a timeo"吗?有多种方法可以将其用作组件,以使手头的任务更容易。在坐下来编写代码之前,您可能还想考虑一下您希望k ["abc", "", "def"] 产生什么——应该是["bcd", "", "efa"],还是["bc", "d", "efa"],还是什么?
  • 讨论了同样的问题here

标签: haskell


【解决方案1】:

让我们看看。

-- k [ "once","upon","a","time"] =
--   [  "nceu","pona","t","imeo"] 

k [] = []
k (x:xs)   =  g (take … x) (drop 1 … : xs)
g o (x:y:xs) =  (x ++ take 1 …) : g … (drop 1 y : xs)
g o [y]   =  [… ++ o]
g _ []   =  []  -- never used; keep compiler happy

您需要完成此代码。

如果您不熟悉++take 和/或drop,则必须自己实现它们。您可以根据在此代码中的使用来计算出需求和实现。

尤其是drop 1 x =~= tail xtake 1 x =~= [head x],但更好(不会导致空输入错误)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    • 2019-12-18
    • 2015-11-12
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    相关资源
    最近更新 更多