简体   繁体   English

Haskell:使用递归比较两个字符串并写出位置和长度

[英]Haskell : Use recursion to compare two strings and write out position + length

I'm new to programming and just started with recursive programming in Haskell. 我是编程的新手,只是从Haskell的递归编程开始。 I could use some help getting started with a problem I want to solve. 我可以使用一些帮助来解决要解决的问题。

I'm looking for a simple way of solving following problem: 我正在寻找一种解决以下问题的简单方法:

compareReverseStrings :: String -> [(Position, Length)] compareReverseStrings ::字符串-> [(位置,长度)]

Examples: 例子:

      compareReverseStrings "ABCDEEEEEFG" = [(5,3)]


      compareReverseStrings "1234444567444447" = [(4,3), (11,3)]

(In this case the funtion compares "ABCDEEEFG" and "GFEEEEEDCBA" in example 1) (在这种情况下,功能将比较示例1中的“ ABCDEEEFG”和“ GFEEEEEDCBA”)

(the function compares "1234444567444447" and "7444447654444321" in example 2) (该函数将示例2中的“ 1234444567444447”和“ 7444447654444321”进行比较)

Let me know if I'm being unclear :) Thank you in advance! 如果我不清楚,请告诉我:)预先谢谢!

Note that the comparison is independent of the reversal; 注意,比较与反转无关。 that is, you can implement your function as the composition of two separate functions 也就是说,您可以将功能实现为两个独立功能的组合

compareReverseStrings str = compareStrings str (reverseString str)
-- Using the Applicative instance of functions, 
-- compareReverseStrings = compareStrings <*> reverseString

Then you can implement the two functions separately. 然后,您可以分别实现这两个功能。 ( reverseString should be trivial; it's already implemented as reverse , but you can write your own definition for practice if you like). reverseString应该是微不足道的;它已经实现为reverse ,但是您可以根据需要编写自己的定义以进行练习)。

compareStrings :: String -> String -> [(Position, Length)]
compareStrings x y = ...
-- Hint: consider what you might do with the result of zip3 [1..] x y
-- What if the letters in the first element are the same?
-- What if they are different?

reverseString :: String -> String
reverseString str = ...

In general, this is how you solve all problems in programming: break your problem down into smaller pieces, solve the subproblems, then combine the results to get the solution to your original problem. 通常,这是解决编程中所有问题的方式:将问题分解为较小的部分,解决子问题,然后组合结果以获取原始问题的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM