BudiBadu Logo
Samplebadu

Haskell by Example: Type Signatures

GHC 9.x

Declaring explicit types for functions and values with this sample code demonstrating type signature syntax using double colon, curried function types with arrow notation, type inference capabilities, and IO type for side effects.

Code

-- Function that adds two integers
add :: Int -> Int -> Int
add x y = x + y

-- Function that checks if a number is even
isEven :: Int -> Bool
isEven n = n `mod` 2 == 0

-- A constant value
piValue :: Double
piValue = 3.14159

-- Main function
main :: IO ()
main = do
    print (add 5 3)
    print (isEven 10)

Explanation

Haskell features a strong, static type system where every expression has a type known at compile time. While Haskell's type inference can deduce types automatically, explicit type signatures using the double colon :: operator are considered standard practice for top-level functions, serving as documentation and enabling better compiler error messages. The double colon is read as "has type of".

Function type signatures use the arrow -> to separate parameters and return types in a curried style. The signature Int -> Int -> Int describes a function taking one Int and returning a function that takes another Int and returns an Int. This currying is fundamental to Haskell, allowing partial application where functions can be called with fewer arguments than defined, returning a new function expecting the remaining arguments.

Basic Haskell types include Int for fixed-precision integers, Integer for arbitrary-precision integers, Double and Float for floating-point numbers, Bool for booleans, Char for characters, and String for text. The IO () type signature indicates functions performing Input/Output operations, with () representing the unit type similar to void in other languages, signifying no meaningful return value.

Code Breakdown

2
add :: Int -> Int -> Int curried function type, takes two Ints returns Int.
6
Int -> Bool function taking Int parameter, returning Bool result.
10
piValue :: Double constant value with explicit type annotation.
14
IO () type for side effects, unit type indicates no return value.