Home > Blockchain >  Haskell -- Fill the List With Empty Spaces
Haskell -- Fill the List With Empty Spaces

Time:11-08

I'm implementing a function that takes a [[Int]], and return a [String], it needs to fill the empty place in each sublist with _s, which index is the complement of the input list, and generate a string from the list, the length of each string is the same and is the (maximum of the input number 1).

For example, if the input is [[1, 2] [0, 1, 2, 3] [1, 3] [0, 2, 3]], the output would be ["_12_", "0123", "_1_3", "0_23"]

I tried my best to do this, and don't know how to insert empty space into the missing part.

getString :: [[Int]] -> [String]
getString x = concat. show. x insert _ 
   where insert _ [] ys = ys

CodePudding user response:

Breaking this down, it seems you need to find the minimum and maximum numbers present.

inputs = [[1, 2], [0, 1, 2, 3], [1, 3], [0, 2, 3]]

listMin = foldl1 min
listMax = foldl1 max

minInput = listMin $ map listMin inputs
maxInput = listMax $ map listMax inputs

We can now readily generate a list from the minimum to the maximum.

ghci> [minInput .. maxInput]
[0,1,2,3]

So now we can map over our inputs with a list comprehension:

[... | x <- inputs]

And let's return a list of all of the digits each time, and use Data.Char.intToDigit to make them characters.

ghci> [[intToDigit y | y <- [minInput..maxInput]] | x <- inputs]
["0123","0123","0123","0123"]

This looks closer, but we actually want '_' if y is not in x. Easy enough with elem.

ghci> :{
ghci| [[if y `elem` x then intToDigit y else '_' 
ghci|        | y <- [minInput..maxInput]] 
ghci|        | x <- inputs]
ghci| :}
["_12_","0123","_1_3","0_23"]

CodePudding user response:

I would advise to start with a simpler problem: doing this for a sublist, so map [1,2] to "_12" and [1,3] to "_1_3". Later you can then do padding at the right of underscores to draw a rectangular matrix. You can do this with recursion where you use an accumulator that will each time check if the head of the list is less than, greater than or equal to the accumulator, so:

getRow :: [Int] -> String
getRow = go 0
    where go _ [] = …
          go i (x:xs)
              | … = …
              | otherwise = …

Here go is thus a helper function. It starts with go 0 [1,2]. We see that 0 is less than 1, so we yield an underscore and advance to go 1 [1,2], since now i is the same as the head of the list, we emit the number as character, etc. I leave implementing the parts as an exercise.

  • Related