갈루아의 반서재

Haskell has a static type system. The type of every expression is known at compile time.
Haskell has type inference.
A type is a kind of label that every expression has. It tells us in which category of things that expression fits.
By using the :t comma, GHCI examine the types of some expressions.

  1. ghci> :t 'a'  
  2. 'a' :: Char  
  3. ghci> :t True  
  4. True :: Bool  
  5. ghci> :t "HELLO!"  
  6. "HELLO!" :: [Char]  
  7. ghci> :t (True'a')  
  8. (True'a') :: (BoolChar)  
  9. ghci> :t 4 == 5  
  10. 4 == 5 :: Bool  

:: is read as "has type of".
Explicit types are always denoted with the first letter in capital case. 'a'
The square brackets  [] denote a list.

Functions also have types. We can choose to give function an explicit type declaration. 

removeNonUppercase
 :: [Char] -> [Char]  
  1. removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]   
removeNonUppercase has a type of [Char] -> [Char]. It takes one string as a parameter and returns another as a result. The [Char] type is synonymous with String.

How to write out the type of a function that takes several parameters
  1. addThree :: Int -> Int -> Int -> Int  
  2. addThree x y z = x + y + z  
The parameters are separated with -> and there's no special distinction between the parameters and the return type.
The return type is the last item in the declaration and the parameters are the first three.

Functions are expressions too, so :t works on them without a problem.

<Overview of some common types>
Int stands for integer. It's used for whole numbers. Int is bounded, which means that it has a minimum and a maximum value. 
Integer stands for also integer. The main difference is that it's not bounded (big. Int).
  1. factorial :: Integer -> Integer  
  2. factorial n = product [1..n]  
  1. ghci> factorial 50  
  2. 30414093201713378043612608166064768844377641568960512000000000000  

Float is a real floating point with single precision.

  1. circumference :: Float -> Float  
  2. circumference r = 2 * pi * r  
  1. ghci> circumference 4.0  
  2. 25.132742  

Double is a real floating point with double the precision!

  1. circumference' :: Double -> Double  
  2. circumference' r = 2 * pi * r  
  1. ghci> circumference' 4.0  
  2. 25.132741228718345  

Bool is a boolean type. It can have only two values: True and False.

Char represents a character. It's denoted by single quotes. A list of characters is a string.

Tuples are types but they are dependent on their length as well as the types of their components, so there is theoretically an infinite number of tuple types. 

Empty tuple () is also a type which can only have a single value: ()

본 카테고리의 내용은 Learn You a Haskell for Great Good! 의 내용을 학습을 위해 요약한 것입니다.