Hammad
Hammad

Reputation: 43

Modifying and Adding to a list in Haskell

I am implementing Burrows-Wheeler Transformation in Haskell. A combination of all cycled strings is generated and stored in a matrix as the first step of the transform. I am using Haskell List to construct the matrix. The list will store the original word on list head and its cyclic combinations down in tail.

Here is an Example of a transformed word

I have written a function that outputs the first cycled string. However, if I call the function again as a recursion, I face an infinite loop.

Here is the function

type BWT = [String] -- List of Strings for Burrows Wheeler matrix
samplebwt = ["BANANA$"] -- Sample input

rotateBWT:: BWT -> BWT
rotateBWT a = if (head (last a)) /= '$' 
    then [tail (head a) ++ [head (head a)]] ++ rotateBWT [tail (head a) ++ [head (head a)]] 
    else a

    rotateBWT samplebwt 
-- returns ["ANANA$B"]
--expected output ["ANANA$B", "NANA$BA", "ANA$BNA", "NA$BANA", "A$BANAN", "$BANANA"]

What am I missing?

Upvotes: 0

Views: 171

Answers (1)

TeWu
TeWu

Reputation: 6564

You can get into infinite loop when you invoke rotateBWT on string that doesn't contain $ character.

There you have a solution that generate output you've shown in example:

type BWT = [String] -- List of Strings for Burrows Wheeler matrix

genBWTmatrix :: String -> BWT
genBWTmatrix str = rotateBWT [str ++ "$"]

rotateBWT :: BWT -> BWT
rotateBWT a = if (head l) == '$' then a
              else a ++ rotateBWT n
                where l = last a
                      n = [(tail l) ++ [head l]]

main = mapM_ putStrLn $ genBWTmatrix "BANANA" -- Prints: BANANA$
                                              --         ANANA$B
                                              --         NANA$BA
                                              --         ANA$BAN
                                              --         NA$BANA
                                              --         A$BANAN
                                              --         $BANANA

Run it

Upvotes: 1

Related Questions