Skip to main content

Problem Sheet for LI Functional Programming - Week 5 & 6

Directories

Consider the following data type for directories.

data File = File {
fileName :: String,
contents :: String
} deriving Show

data Directory = Directory {
dirName :: String,
subdirs :: [ Directory ],
files :: [ File ]
} deriving Show
  1. Create your own sample directory structure

  2. Write a function to return a list of all the files.

  3. Here is a function to find a substring and return its index:

    import Data.List

    findString :: (Eq a) => [a] -> [a] -> Maybe Int
    findString search str = findIndex (isPrefixOf search) (tails str)

    Write a function to search the directory for a file containing some string.

  4. Write a function to search for files by name

  5. Modify the File type to contain different types of data: binary (you may wish to look at ByteString from the Haskell prelude) and string. Write functions to find all binary or text files in the given director structure.

  6. Write a function to sort the directory contents alphbetically.

  7. Harder Write a function to print the directory contents as a text tree.

XML

Consider the following simplified data type for representing XML documents:

data Element  = Element {
elName :: String,
elAttribs :: [Attr],
elContent :: [Content]
} deriving Show

data Content = Elem Element
| Text String
deriving Show

data Attr = Attr {
attrKey :: String,
attrVal :: String
} deriving (Eq, Show)
  1. Encode the following example:

    <person gender="female">
    <firstname>Anna</firstname>
    <lastname>Smith</lastname>
    </person>
  2. Encode the following example:

    <note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
    </note>
  3. Write a function which returns all elements containing only text in their content

  4. Write a function which returns all elements which have exactly one child element

  5. Write a function which searches for all elements with a given attribute key

  6. Write a function which formats the XML data to a string

  7. Harder Write a function to parse XML text to the above data type


You can continue with examples like the above by inventing your own transformations and queries on the directory and XML examples. Be creative!