niedziela, lutego 22, 2009

Instancja klasy Show dla funkcji

Wbrew pozorom łatwo napisać taką instancję. Nie będzie ona spełniała warunku
> (read . show) == id
ale może być użyteczna. Można ją znaleźć w przypadku GHC 6.10 w module Text.Show.Functions. Wygląda ona tak:

instance Show (a -> b) where
     showsPrec _ _ = showString "<function>"

Dzisiaj wpadłem na nieco pożyteczniejszą formę. Niestety, wszystko ma swoją cenę - zadziała ona tylko dla funkcji których argumenty są elementami klasy Typeable.

instance (Typeable a, Typeable b) => Show (a -> b) where
     show _ = "<function: " ++ show (typeOf (undefined :: a)) ++ " -> " ++ show (typeOf (undefined :: b)) ++ ">"

Przykładowe działanie:
*Main> print print
Loading package syb ... linking ... done.
<function: () -> IO ()>
*Main> :set -Wall
*Main> print print

<interactive>:1:6:
     Warning: Defaulting the following constraint(s) to type `()'
         `Show a' arising from a use of `print' at <interactive>:1:6-10
         `Typeable a' arising from a use of `print' at <interactive>:1:0-10
     In the first argument of `print', namely `print'
     In a stmt of a 'do' expression: it <- print print
<function: () -> IO ()>
*Main> print putStrLn
<function: [Char] -> IO ()>
*Main> print id

<interactive>:1:0:
     Ambiguous type variable `a' in the constraint:
         `Typeable a' arising from a use of `print' at <interactive>:1:0-7
     Probable fix: add a type signature that fixes these type variable(s)
*Main> print (id :: Int -> Int)
<function: Int -> Int>
*Main> print (undefined :: Int -> Int -> Int)
<function: Int -> Int -> Int>

Brak komentarzy:

Prześlij komentarz