【问题标题】:Merge list of strings into list of tuple of those strings将字符串列表合并到这些字符串的元组列表中
【发布时间】:2017-08-29 03:13:00
【问题描述】:

我需要这样做:

mergers ["co","nt","ro","la"] ⇒ [("co","ntrola"),("cont","rola")("contro","la")]
mergers ["co","nt"] ⇒ [("co","nt")]
mergers ["co"] ⇒ []

但我不知道怎么做。我最近开始在 Haskell 中编程,一直在尝试解决这个问题。

【问题讨论】:

    标签: string list haskell merge tuples


    【解决方案1】:
    import Data.List (inits, tails)
    
    mergers :: [[a]] -> [([a], [a])]
    mergers xs = init $ tail $ zip (map concat $ inits xs) (map concat $ tails xs)
    

    inits xs返回xs的所有前缀(包括[]和原始列表),tails xs返回xs的所有后缀(包括[]和原始列表)。由于包含了原始列表和[],所以后面我们必须使用inittail

    以下是一些中间结果:

    ghci> inits ["co","nt","ro","la"]
    [[],["co"],["co","nt"],["co","nt","ro"],["co","nt","ro","la"]]
    
    ghci> tails ["co","nt","ro","la"]
    [["co","nt","ro","la"],["nt","ro","la"],["ro","la"],["la"],[]]
    
    ghci> map concat $ inits ["co","nt","ro","la"]
    ["","co","cont","contro","controla"]
    
    ghci> map concat $ tails ["co","nt","ro","la"]
    ["controla","ntrola","rola","la",""]
    
    ghci> let xs = ["co","nt","ro","la"] in zip (map concat $ inits xs) (map concat $ tails xs)
    [("","controla"),("co","ntrola"),("cont","rola"),("contro","la"),("controla","")]
    

    最后一行说明为什么zip 之后的init . tail 是必要的。

    【讨论】:

      【解决方案2】:

      你可以试试这个,作为第一个解决方案:

      a=["12","34","56", "78"]
      g n x= (concat $ fst y, concat $ snd y) where y=splitAt n x
      h a = [g i a|i<-[1..(length a)-1]]
      

      【讨论】:

      • 如何将其放入函数中或调用它?不能是预定值
      • 我不明白这个问题。 h 是你必须调用的函数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 2013-09-04
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      相关资源
      最近更新 更多