'Take every second element from list of lists and square it in Haskell

I am trying to get something like this: [[1,2,3,4],[2,3],[4,5,6,7],[1,2]]=[4,16,9,25,49,4]

First i tried to write function that prints every second element. I still have to square the results.

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

I have accomplished:

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



Solution 1:[1]

You only need to square x, so:

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

and use that in the fun to concatenate the results.

You need to add a Num a => type constraint, since only for numerical types, one can multiply an two values.

Another option is to square the items that are produced by the takeSecond function:

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

Solution 2:[2]

There is a way to do it with one function:

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

This code contains an intentional error, which should be easy to fix after you've understood it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2