]> git.rkrishnan.org Git - yorgey.git/blobdiff - hw7/JoinList.hs
dropJ: handle the negative n case
[yorgey.git] / hw7 / JoinList.hs
index 4edc744bb9dab7df4805db88436a05c957ab4dbd..7f13837e02d6bb79962d1fc654a6df9da70b5f4f 100644 (file)
@@ -2,7 +2,7 @@
 module JoinList where
 
 import Data.Monoid
-
+import Sized
 
 data JoinList m a = Empty
                   | Single m a
@@ -20,3 +20,25 @@ Empty +++ x = x
 x +++ Empty = x
 alst1 +++ alst2 = Append ((tag alst1) `mappend` (tag alst2)) alst1 alst2
 
+-- exercise 2
+-- 1. index
+indexJ :: (Sized b, Monoid b) =>
+          Int -> JoinList b a -> Maybe a
+indexJ _ Empty = Nothing
+indexJ n _ | n < 0 = Nothing
+indexJ _ (Single _ a) = Just a
+indexJ n (Append _ l r) | n < (getSize (size (tag l))) = indexJ n l
+                        | otherwise = indexJ (n - getSize (size (tag l))) r
+
+-- 2. drop
+dropJ :: (Sized b, Monoid b) =>
+         Int -> JoinList b a -> JoinList b a
+dropJ n x | n < 0 = x
+dropJ 0 x = x
+dropJ _ Empty = Empty
+dropJ _ (Single _ _) = Empty
+dropJ n x | (getSize (size (tag x))) < n = Empty
+dropJ n (Append _ l r) | n > (getSize (size (tag l))) =
+                           dropJ (n - getSize (size (tag l))) r
+                       | otherwise = let lft = dropJ n l in
+                                     Append ((tag lft) `mappend` (tag r)) lft r