【问题标题】:Haskell : Use recursion to compare two strings and write out position + lengthHaskell:使用递归比较两个字符串并写出位置+长度
【发布时间】:2017-04-03 06:36:00
【问题描述】:

我是编程新手,刚开始使用 Haskell 进行递归编程。我可以使用一些帮助来开始解决我想要解决的问题。

我正在寻找解决以下问题的简单方法:

compareReverseStrings :: String -> [(Position, Length)]

例子:

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


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

(在这种情况下,函数比较示例 1 中的“ABCDEEEFG”和“GFEEEEEDCBA”)

(函数比较例2中的“1234444567444447”和“7444447654444321”)

如果我不清楚,请告诉我 :) 提前谢谢!

【问题讨论】:

    标签: string haskell recursion


    【解决方案1】:

    请注意,比较与反转无关;也就是说,你可以将你的函数实现为两个独立函数的组合

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

    然后就可以分别实现这两个功能了。 (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 = ...
    

    一般来说,这就是您解决编程中所有问题的方法:将问题分解成更小的部分,解决子问题,然后将结果组合起来以获得原始问题的解决方案。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 2018-03-01
      • 2015-10-25
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多