从列表列表中每隔一秒提取一个元素,并在Haskell中进行平方



我正试图得到这样的东西:[[1,2,3,4],[2,3],[4,5,6,7],[1,2]]=[4,16,9,25,49,4]

首先,我试图编写一个函数,每隔一秒打印一个元素。我仍然需要对结果进行平方运算。

takeSecond :: [a] -> [a]
takeSecond [] = []
takeSecond [a] = []
takeSecond (y:x:xs) = [x] ++ takeSecond xs

fun :: [[a]] -> [a]
fun [] = []
fun (x:xs) = (takeSecond x) ++ (fun xs)

我已经完成了:

[[1,2,3,4],[2,3],[4,5,6,7],[1,2]]=[2,4,3,5,7,2]

您只需要将x平方,因此:

takeSecondSquared ::Num a =>[a] -> [a]
takeSecondSquared (_:x:xs) =x*x: takeSecond xs
takeSecondSquared _ = []

并在CCD_ 2中使用它来连接结果。

您需要添加Num a =>类型约束,因为只有对于数字类型,可以将两个值相乘。

另一种选择是将takeSecond功能产生的项目平方:

fun :: [[a]] -> [a]
fun [] = []
fun (x:xs) =map (x -> x * x)takeSecond x ++ fun xs

有一种方法可以用一个函数来实现:

foo :: (Num a) => [[a]] -> [a]
foo ((_:b:c):xs) = b*b : foo ((b:c):xs)
foo (_:xs) = foo xs
foo _ = []

这个代码包含一个故意的错误,在你理解它之后应该很容易修复

最新更新