使用 foldl 函数将字符串列表转换为元组列表

transform a list of string to list of tuples using foldl function

我有以下功能:

fn :: [String] -> [(a,b,c)]
fn lst = case lst of
  [] -> []
  (a:b:c:xs) -> (a,b,c) : fn xs

我想使用 foldlfoldr

编写此函数

I want to write this function using foldl or foldr

这有点丑陋,但它在技术上用 foldr 解决了它(它很容易适应 foldl):

fn :: String -> [(Char, Char, Char)]                                                                                                                                                                    
fn s = snd $ foldr toTriples ([], []) s where
    toTriples :: Char -> (String, [(Char, Char, Char)]) -> (String, [(Char, Char, Char)])
    toTriples c (cur, tups) | length cur < 2 = (c:cur, tups)
    toTriples c (cur, tups) = ([], (c, cur!!0, cur!!1):tups)

作为累加器,它使用一对cur,元组的当前部分被扫描,和tups,一个元组列表。

  • 如果 cur 的长度小于 2,它会将当前字符添加到它前面。

  • 如果 cur 的长度为 2,它会创建一个元组并将其添加到元组列表中。