Home > Back-end >  Take every second element from list of lists and square it in Haskell
Take every second element from list of lists and square it in Haskell

Time:02-22

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]

CodePudding user response:

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

CodePudding user response:

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.

  • Related