Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell map (?) operation with different first and last functions

I am writing a Haskell function that operates on a list of ByteString values. I need to do a different operation on the first and last items (which may be the same if the list has only one item).

Specifically, I want to write out the following:

  "item-1\
  \item-2\
  \item-3\
  ...
  \item-n"

where item-1 starts with a double quote and ends with a backslash and item-n starts with a backslash and ends with a double quote. All items between item-1 and item-n start and end with backslashes. I am emitting a base64 encoded value as a Haskell String for some code generation. I have already broken the original (long) base64-encoded ByteString into chunks that are 64 characters long each.

like image 747
Ralph Avatar asked Sep 20 '25 15:09

Ralph


2 Answers

I just realized that my question is a dumb one.

I can just use intercalate to inject the "\\\n\\" between the items and then prepend and append a double quote:

import qualified Data.ByteString.Lazy.Char8 as L
(L.pack "\"") `L.append` (L.intercalate "\\\n\\" items) `L.append` (L.pack "\"")

Sample output:

"H4sIAAAAAA\
\AAA2NgAAMm\
\CMXA7JRYxI\
\Am5JafD2Uy\
\AgDvdHs6Lg\
\AAAA==\
\"
like image 190
Ralph Avatar answered Sep 22 '25 05:09

Ralph


You can also consider splitting your list using:

  • "head" to get the first element of the list
  • "tail" to get all but the first element of the list
  • "init" to get all but the last element of the list
  • "last" to get the last element of the list

So [head a] ++ init (tail a) ++ [last a] == a.

That way, you can change the first and last elements of the list individually and map a function over the "init" part.

like image 39
Alfonso Villén Avatar answered Sep 22 '25 05:09

Alfonso Villén