gpt4 book ai didi

haskell - Haskell 中的列表到元组

转载 作者:行者123 更新时间:2023-12-02 15:20:16 24 4
gpt4 key购买 nike

假设我有一个这样的列表:

["Questions", "that", "may", "already", "have", "your", "correct", "answer"]

并且想要这个:

[("Questions","that"),("may","already"),("have","your"),("correct","answer")]

这可以做到吗?或者这是一个糟糕的 Haskell 实践?

最佳答案

对于一个简单的方法(对于奇数个元素失败),您可以使用

combine :: [a] -> [(a, a)]
combine (x1:x2:xs) = (x1,x2):combine xs
combine (_:_) = error "Odd number of elements"
combine [] = []

Live demo

或者您可以使用一些复杂的方法,例如我不太想理解的其他答案。

更通用:

map2 :: (a -> a -> b) -> [a] -> [b]
map2 f (x1:x2:xs) = (f x1 x2) : map2 f xs
map2 _ (_:_) = error "Odd number of elements"
map2 _ [] = []

关于haskell - Haskell 中的列表到元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com