Understand return function type of error function

:t error

shows

error :: [Char] -> a

To understand what type a is, I wrote this test code,

import Data.Typeable
custom = error "hello how are you"

main = do
  let a = custom
  putStrLn $ show (typeOf a)

It gets the return value of the function errorand tries to print it using the show function. It gives an error like,

ab.hs:6:20:
    No instance for (Typeable a0) arising from a use of ‘typeOf’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance [overlap ok] Typeable ()
        -- Defined in ‘Data.Typeable.Internal’
      instance [overlap ok] Typeable Bool
        -- Defined in ‘Data.Typeable.Internal’
      instance [overlap ok] Typeable Char
        -- Defined in ‘Data.Typeable.Internal’
      ...plus 14 others

How can I do typeOffor a variable and print it as a string?

+4
source share
2 answers

ais a lowercase case, which means its type variable. It can take any type. You can substitute the result errorfor any expression, and your code will enter validation. This is useful for partial functions that are not defined for all possible arguments. For instance:

head :: [a] -> a
head [] = error "empty list"
head (x:_) = x

, , . error , .

Per 5402 :

error "add" , .

+4

typeOf , Haskell TypeRep, . , , typeOf , , .

, typeOf , typeOf (error "") - "a" "forall a. a", , .

typeOf error, typeOf (error "" :: String) typeOf (error "" :: Int), "String" "Int" .

+2

Source: https://habr.com/ru/post/1599815/


All Articles