March 23, 2012

haskell - я не знаю

module Main where

class Ff f where
   ffmap :: (a -> b) -> (f a -> f b)

instance Ff [] where
   ffmap f [] = []
   ffmap f (x:xs) = (f x):(ffmap f xs)

class (Ff f) => Sz f where
   fsz :: (a -> b -> c) -> f a -> f b -> f c
   fszu :: a -> f a

instance Sz [] where
   fsz f [] _          = []
   fsz f _ []          = []
   fsz f (x:xs) [y]    = (f x y):(map (\x -> f x y) xs)
   fsz f [x] (y:ys)    = (f x y):(map (f x) ys)
   fsz f (x:xs) (y:ys) = (f x y):(fsz f xs ys)
   fszu x             = [x]

instance (Sz f, Num a, Show (f a), Eq (f a)) => Num (f a) where
   xs + ys       = fsz (+) xs ys
   xs - ys       = fsz (-) xs ys
   xs * ys       = fsz (*) xs ys
   abs xs        = ffmap abs xs
   signum xs     = ffmap signum xs
   fromInteger i = fszu (fromInteger i)

r = 1+[4,5,6]
r2 = [1,2,3]+[4,5,6]

main = putStrLn $ show $ r++r2

updated: результат:

$ runhaskell.exe -XFlexibleInstances -XUndecidableInstances apl.hs
[5,6,7,5,7,9]

Подскажите, plz, кто шарит, я пока через типы классов не пробрался, а это просто скопипастил из интернета.