{-# OPTIONS_GHC -cpp -fglasgow-exts #-} import Data.Array.Base import Data.Array.IO import Data.Array.IArray import Data.Array.MArray class ListLike c e where nullL :: c e -> Bool headL :: c e -> e tailL :: c e -> c e instance ListLike [] e where nullL = null headL = head tailL = tail instance ListLike Slice e where nullL = nullS headL = headS tailL = tailS -- Instance of ListLike: slice over a regular array data Slice e = Slice Int (Array Int e) arraySlice arr | (0,_) <- bounds arr = Slice 0 arr listSlice xs = arraySlice (listArray (0,length(xs)-1) xs) nullS (Slice n arr) = n>hi where (0,hi) = bounds arr headS (Slice n arr) = arr!n tailS (Slice n arr) = Slice (n+1) arr -- Definitions of functions which use ListLike interface -- to process any list or array foldrL :: (ListLike c a) => (a -> b -> b) -> b -> c a -> b foldrL k z xx | nullL xx = z | otherwise = x `k` foldrL k z xs where x = headL xx xs = tailL xx lengthL xs = foldrL (\_->(+1)) 0 xs sumL xs = foldrL (+) 0 xs prodL xs = foldrL (*) 1 xs main = do print$ lengthL [1..10] print$ lengthL (listSlice [1..10]) print$ sumL [1..10] print$ sumL (listSlice [1..10])