我想创建一个函数,它接受一个列表["1","2","3","4"],并返回一个元组列表[(1,2(,(3,4(],但我不知道如何进行编码
every n xs = case drop (n-1) xs of
(y:ys) -> y : every n ys
[] -> []
tup :: [String] -> [(Int, Int)]
tup xs = [((read c),(read i)) | c <- (every 1 xs), i <-(every 2 xs)]
是我试过的,但输出错误
输出:
*Main> tup ["1", "2", "3", "4"]
[(1,2),(1,4),(2,2),(2,4),(3,2),(3,4),(4,2),(4,4)]
您可以使用模式匹配:
tup [] = []
tup [_] = []
tup (a:b:other) = (read a, read b):(tup other)
前两种情况处理的是空列表和一个元素的列表。从这些元组中构造一个元组列表是没有意义的,所以函数只返回空列表。最后一种情况只是提取两个前导值,将它们放入一个元组中,并将其作为递归调用返回的任何值的前缀。