728x90
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.
- ghci> :t 'a'
- 'a' :: Char
- ghci> :t True
- True :: Bool
- ghci> :t "HELLO!"
- "HELLO!" :: [Char]
- ghci> :t (True, 'a')
- (True, 'a') :: (Bool, Char)
- ghci> :t 4 == 5
- 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]
- 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
- addThree :: Int -> Int -> Int -> Int
- 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).
- factorial :: Integer -> Integer
- factorial n = product [1..n]
- ghci> factorial 50
- 30414093201713378043612608166064768844377641568960512000000000000
Float is a real floating point with single precision.
- circumference :: Float -> Float
- circumference r = 2 * pi * r
- ghci> circumference 4.0
- 25.132742
Double is a real floating point with double the precision!
- circumference' :: Double -> Double
- circumference' r = 2 * pi * r
- ghci> circumference' 4.0
- 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! 의 내용을 학습을 위해 요약한 것입니다.
728x90
'프로그래밍 Programming' 카테고리의 다른 글
Haskell_ 003 Typeclass (0) | 2018.03.15 |
---|---|
Haskell_ 002 Type variables (0) | 2018.03.09 |
하스켈 패키지 삭제하기 How to uninstall a Haskell package installed with stack? (0) | 2018.02.06 |
cabal install 사용방법 (1) How to cabal install (1) (0) | 2018.02.06 |
Haskell Yesod의 템플릿 언어 세익스피어를 활용하여 웹페이지 만들기 (2) (0) | 2018.02.03 |