listhaskellzipwith

Haskell, zip the element of a list with its length


The next lines should show how its has to work..

[14,2,344,41,5,666] after [(14,2),(2,1),(344,3),(5,1),(666,3)]

["Zoo","School","Net"] after [("Zoo",3),("School",6),("Net",3)]

Thats my code up to now

zipWithLength :: [a] -> [(a, Int)]
zipWithLength (x:xs) = zipWith (\acc x -> (x, length x):acc) [] xs

I want to figure out what the problem in the second line is.


Solution

  • After installing the number-length package, you can do:

    module Test where
    import           Data.NumberLength
    
    -- use e.g for list of String
    withLength :: [[a]] -> [([a], Int)]
    withLength = map (\x -> (x, length x))
    
    -- use e.g for list of Int
    withLength' :: NumberLength a => [a] -> [(a, Int)]
    withLength' = map (\x -> (x, numberLength x))
    

    Examples:

    >>> withLength ["Zoo", "bear"]
    [("Zoo",3),("bear",4)]
    >>> withLength' [14, 344]
    [(14,2),(344,3)]