[Haskell-cafe] A type class puzzle

Yitzchak Gale gale at sefer.org
Tue Oct 31 04:02:03 EST 2006


Consider the following sequence of functions
that replace a single element in an n-dimensional
list:

replace0 :: a -> a -> a
replace0 = const

replace1 :: Int -> a -> [a] -> [a]
replace1 i0 x xs
 | null t    = h
 | otherwise = h ++ (replace0 x (head t) : tail t)
 where (h, t) = splitAt i0 xs

replace2 :: Int -> Int -> a -> [[a]] -> [[a]]
replace2 i0 i1 x xs
 | null t    = h
 | otherwise = h ++ (replace1 i1 x (head t) : tail t)
 where (h, t) = splitAt i0 xs

etc.

Generalize this using type classes.


More information about the Haskell-Cafe mailing list