]> git.rkrishnan.org Git - yorgey.git/blob - hw7/StringBuffer.hs
hw7: starting materials
[yorgey.git] / hw7 / StringBuffer.hs
1 {-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
2 module StringBuffer where
3
4 import Data.Monoid
5
6 import Buffer
7
8 instance Buffer String where
9   toString     = id
10   fromString   = id
11   line n b     = safeIndex n (lines b)
12   replaceLine n l b = unlines . uncurry replaceLine' . splitAt n . lines $ b
13       where replaceLine' pre [] = pre
14             replaceLine' pre (_:ls) = pre ++ l:ls
15   numLines     = length . lines
16   value        = length . words
17
18 safeIndex :: Int -> [a] -> Maybe a
19 safeIndex n _ | n < 0 = Nothing
20 safeIndex _ []        = Nothing
21 safeIndex 0 (x:_)     = Just x
22 safeIndex n (_:xs)    = safeIndex (n-1) xs