기본
Hello World
main이 진입점, putStrLn은 줄바꿈과 함께 출력합니다
-- GHCi interactive environment
-- launch: ghci (quit with :q)
-- simple arithmetic
> 2 + 3
5
-- function application (no parentheses needed)
> succ 5
6
-- define a function
> double x = x * 2
> double 10
20
-- lists
> [1,2,3,4]
[1,2,3,4]
-- strings are lists of chars
> "hello"
"hello"주석
{- -}는 여러 줄 주석용
-- single line comment
{- multi-line comment
spanning multiple lines -}
{- nested {- comments -} are allowed -}
-- comments are ignored by the compilerGHCi 대화형
:t는 타입 표시, :q는 종료
-- hello.hs
main :: IO ()
main = putStrLn "Hello, World!"
-- run interpreted
-- runhaskell hello.hs
-- or compile to an executable
-- ghc hello.hs && ./hellolet 바인딩
let은 do 블록에서 지역 변수를 정의합니다
-- in GHCi, 'let' defines a binding (no 'in' needed)
> let x = 5
> let double n = n * 2
> x + double x
15
-- in a source file, top-level bindings need no 'let'
y = 10
-- 'let' inside an expression needs 'in'
z = let a = 2 in a * a -- 4들여쓰기 규칙
Haskell은 중괄호 대신 들여쓰기를 사용합니다
-- :t shows the type of an expression
> :t 'a'
'a' :: Char
> :t True
True :: Bool
> :t "hi"
"hi" :: [Char]
> :t (+)
(+) :: Num a => a -> a -> a
-- :info shows typeclass info
> :info Num파일 로드
:load는 모듈을 GHCi로 불러오고, :reload는 수정 뒤 다시 불러옵니다. :browse는 모듈이 수출하는 모든 것을 나열합니다. :main은 커맨드라인 인수와 함께 프로그램을 실행합니다. 이들이 REPL 워크플로우를 부드럽게 합니다.
-- GHCi commands
> :load MyModule.hs -- or :l
> :reload -- or :r, reload after edits
> :type main -- check a type
> :browse Data.List -- list a module's exports
> :main arg1 arg2 -- run main with args
-- :set +t auto-prints types of results타입
기본 타입
::는 타입을 명시적으로 주석 처리합니다
-- Int: bounded integer (platform-dependent)
x :: Int
x = 9
-- Integer: arbitrary-precision (unbounded)
big :: Integer
big = 2 ^ 100
-- Float / Double (prefer Double)
piVal :: Double
piVal = 3.14159
-- Bool
flag :: Bool
flag = True
-- Char (single Unicode character)
c :: Char
c = 'a'함수 타입
->는 오른쪽 결합, 마지막이 반환 타입입니다
-- explicit type signature above a binding
age :: Int
age = 30
-- annotate an expression inline with ::
result = (5 :: Int) + 3
-- function signature
add :: Int -> Int -> Int
add x y = x + y
-- annotate a list
nums :: [Double]
nums = [1.0, 2.0, 3.0]타입 변수
소문자는 타입 변수입니다
-- 'a' is a type variable (polymorphic)
id' :: a -> a
id' x = x
-- works for any type
> id' 5
5
> id' "hello"
"hello"
-- length works on any list
length :: [a] -> IntMaybe 타입
Maybe는 실패할 수 있는 계산을 나타냅니다
-- '->' is right-associative
add :: Int -> Int -> Int
-- equivalent to: Int -> (Int -> Int)
-- takes a function as an argument
apply :: (a -> b) -> a -> b
apply f x = f x
-- returns a function
const' :: a -> b -> a
const' x y = xEither 타입
Either는 오류 처리에 사용됩니다
-- Maybe: optional values
data Maybe a = Nothing | Just a
safeDiv :: Double -> Double -> Maybe Double
safeDiv _ 0 = Nothing
safeDiv x y = Just (x / y)
-- Either: a value or an error
data Either a b = Left a | Right b
-- convention: Left = error, Right = success
parse :: String -> Either String Int
parse s = Right (read s)튜플 & 리스트 타입
튜플 (a, b)는 다른 타입일 수 있는 고정 개수의 값을 담습니다. 리스트 [a]는 같은 타입의 임의 개수 값을 담습니다. 튜플의 타입은 크기를 인코딩하지만, 리스트의 타입은 그렇지 않습니다.
-- tuple: (a, b)
pair :: (Int, String)
pair = (1, "one")
-- list: [a]
nums :: [Int]
nums = [1, 2, 3]
-- list of tuples
pairs :: [(Int, String)]
pairs = [(1, "a"), (2, "b")]
-- empty list keeps the polymorphic type
empty :: [a]
empty = []타입 클래스
Eq 타입 클래스
Eq는 동등성 비교를 정의합니다
-- name, parameters, '=', body
double :: Int -> Int
double x = x * 2
-- application: just a space, no parentheses
> double 5
10
-- multiple parameters (curried)
add :: Int -> Int -> Int
add x y = x + y
> add 3 4
7Show와 Read
Show/Read 타입 클래스
-- application is left-associative
> max 3 5
5
> max (max 3 5) 7
7
-- '$' has the lowest precedence, right-associative
> sum (map (*2) [1..5])
30
> sum $ map (*2) [1..5] -- same, fewer parens
-- chain reads left to right
> putStrLn $ show $ sum [1..10]
55Num과 Ord
Num은 숫자 연산, Ord는 순서 비교용
-- wrap an operator in () to use as a function
> (+) 2 3
5
> (*) 4 5
20
-- sections: partial application of operators
> (+10) 5
15
> (3/) 12
0.25
> (/3) 12
4.0
-- backticks make a function infix
> 10 `div` 3
3
> 10 `mod` 3
1Functor 타입 클래스
Functor는 매핑 가능합니다
-- (.) composes functions right to left
(.) :: (b -> c) -> (a -> b) -> a -> c
(f . g) x = f (g x)
> negate . sum $ [1,2,3]
-6
-- chaining
fn = ceiling . negate . tan
> fn (pi/4)
-1
-- point-free style
odd' = not . even타입 제약
=>의 왼쪽이 타입 제약입니다
-- functions are first-class values
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
> applyTwice (+3) 10
16
> applyTwice (\x -> x*x) 2
16
-- pass functions to higher-order functions
> map (*2) [1..5]
[2,4,6,8,10]
> filter even [1..6]
[2,4,6]중위 & 전위
모든 이항 함수는 백틱 사이에 중위로 쓸 수 있고(3 `elem` xs), 모든 연산자는 괄호 안에 전위로 쓸 수 있습니다(mod 10 3). 맥락에서 더 자연스럽게 읽히는 쪽을 고르세요.
-- infix operators can be written prefix with ()
> mod 10 3
1
> div 10 3
3
-- functions can be written infix with backticks
> 10 `mod` 3
1
> 10 `div` 3
3
-- elem: membership test, often infix
> 3 `elem` [1,2,3]
True함수
함수 정의
함수 호출에 괄호가 필요 없습니다
-- lists are homogeneous linked lists
nums :: [Int]
nums = [1, 2, 3, 4, 5]
-- strings are [Char]
chars = ['h','e','l','l','o']
str = "hello" -- same as chars
-- empty list
empty = []
-- cons (prepend) is O(1)
> 0 : [1,2,3]
[0,1,2,3]다중 매개변수 함수
모든 함수는 단일 매개변수(커링)입니다
-- ranges
> [1..5]
[1,2,3,4,5]
-- with a step (first two elements)
> [2,4..10]
[2,4,6,8,10]
-- decreasing needs the step
> [5,4..1]
[5,4,3,2,1]
-- infinite lists (lazy)
> take 5 [1..]
[1,2,3,4,5]
> take 3 (cycle [1,2])
[1,2,1]연산자를 함수로
()는 연산자를 함수로 감쌉니다
-- basic access (partial: crash on empty)
> head [1,2,3]
1
> tail [1,2,3]
[2,3]
> last [1,2,3]
3
> init [1,2,3]
[1,2]
-- safe helpers
> length [1,2,3]
3
> null []
True
> reverse [1,2,3]
[3,2,1]함수 합성
. 연산자가 함수를 합성합니다
-- '++' concatenates two lists
> [1,2] ++ [3,4]
[1,2,3,4]
-- ':' prepends a single element (O(1))
> 1 : [2,3]
[1,2,3]
-- concat flattens one level
> concat [[1,2],[3,4],[5]]
[1,2,3,4,5]
-- intercalate joins with a separator
> intercalate ", " ["a","b","c"]
"a, b, c"where 절
where는 함수 하단에 도우미를 정의합니다
-- like mathematical set-builder notation
> [x*2 | x <- [1..5]]
[2,4,6,8,10]
-- with a predicate (filter)
> [x | x <- [1..10], even x]
[2,4,6,8,10]
-- multiple generators = Cartesian product
> [(x,y) | x <- [1,2], y <- ['a','b']]
[(1,'a'),(1,'b'),(2,'a'),(2,'b')]
-- with a let binding
> [x*y | x <- [1..3], let y = x+1]
[2,6,12]흔한 리스트 함수
elem은 멤버십을 검사합니다(보통 중위). sum과 product가 숫자 리스트를 축약합니다. take/drop이 접두사를 추출하거나 제거합니다. splitAt은 인덱스에서 쌍으로 나눕니다. 리스트는 불변이므로 모두 새 리스트를 반환합니다.
-- membership (often written infix)
> elem 3 [1,2,3]
True
> 3 `elem` [1,2,3]
True
-- reductions
> sum [1..10]
55
> product [1..5]
120
-- take / drop a prefix
> take 3 [1..10]
[1,2,3]
> drop 3 [1..10]
[4,5,6,7,8,9,10]
-- split at an index
> splitAt 3 [1..6]
([1,2,3],[4,5,6])패턴 매칭
기본 패턴 매칭
순서대로 매치, _는 모든 것에 매치
-- tuples can hold different types
pair :: (Int, String)
pair = (1, "hello")
triple :: (Int, String, Double)
triple = (1, "x", 3.14)
-- the size is part of the type
-- (1,2) and (1,2,3) are different types리스트 패턴 매칭
:가 head와 tail을 분리합니다
-- fst/snd only work on pairs
> fst (1, "a")
1
> snd (1, "a")
"a"
-- swap exchanges the components
> swap (1, 2)
(2,1)
-- these do NOT work on triples
> fst (1, 2, 3) -- type error!튜플 패턴 매칭
튜플의 각 위치를 매치합니다
-- destructure a tuple by position
describe :: (Int, String) -> String
describe (n, s) = show n ++ ": " ++ s
-- ignore components with _
firstOf :: (a, b, c) -> a
firstOf (x, _, _) = x
-- in a list comprehension
> [n | (n, _) <- [(1,'a'),(2,'b')]]
[1,2]as 패턴
@는 매치된 전체 값을 유지합니다
-- zip pairs elements from two lists
> zip [1,2,3] ['a','b','c']
[(1,'a'),(2,'b'),(3,'c')]
-- stops at the shorter list
> zip [1,2,3] [4,5]
[(1,4),(2,5)]
-- unzip splits a list of pairs
> unzip [(1,'a'),(2,'b')]
([1,2],"ab")case 표현식
함수 본문 내에서 패턴 매칭을 위한 case
-- list: same type, variable length
ints :: [Int]
ints = [1, 2, 3]
-- tuple: mixed types, fixed length
mixed :: (Int, String, Bool)
mixed = (1, "x", True)
-- list of tuples (tabular data)
people :: [(String, Int)]
people = [("Alice",30),("Bob",25)]
-- cannot mix types in a list
> [1, "two"] -- type error가드
기본 가드
otherwise는 True의 별칭입니다
-- match on literals, top to bottom
lucky :: Int -> String
lucky 7 = "LUCKY SEVEN!"
lucky _ = "Sorry, you're out of luck"
> lucky 7
"LUCKY SEVEN!"
> lucky 13
"Sorry, you're out of luck"다중 매개변수 가드
가드는 순서대로 검사합니다
-- empty list
isEmpty [] = True
isEmpty _ = False
-- head and tail (cons pattern)
head' :: [a] -> a
head' (x:_) = x
-- first two elements
firstTwo :: [a] -> [a]
firstTwo (x:y:_) = [x,y]
firstTwo xs = xs가드와 where
where는 모든 가드에서 공유될 수 있습니다
-- match by position
addPair :: (Int, Int) -> Int
addPair (x, y) = x + y
-- nested patterns
getAge :: (String, (Int, Int)) -> Int
getAge (_, (age, _)) = age
-- ignore with _
nameOf :: (String, Int) -> String
nameOf (name, _) = nameas 패턴
as 패턴(name@pattern)은 이름을 매칭된 전체 값에 바인딩하면서 동시에 분해합니다. 원본과 그 부분이 모두 필요할 때 유용하며 비싼 재구성을 피합니다.
-- '@' keeps the whole value AND its parts
firstLetter :: String -> String
firstLetter "" = "Empty string!"
firstLetter all@(x:_) =
"The first letter of " ++ all ++ " is " ++ [x]
> firstLetter "Haskell"
"The first letter of Haskell is H"case 표현식
case는 표현식 안에서 패턴 매칭을 수행합니다. 함수 본문이 셋업 이후 계산된 값에 따라 분기해야 할 때 유용합니다. 패턴은 순서대로 시도되며 필요하면 catch-all을 추가하세요.
-- pattern match inside any expression
describe :: [a] -> String
describe xs =
case xs of
[] -> "empty"
[_] -> "singleton"
_ -> "longer"
-- case on any value, e.g. an Ordering
classify n = case compare n 0 of
LT -> "negative"
EQ -> "zero"
GT -> "positive"생성자 패턴
패턴은 Red, Nothing, Just 같은 데이터 생성자에 매칭될 수 있습니다. 대수적 데이터 타입이 이렇게 분해됩니다. 컴파일러가 비철저 패턴에 경고하므로 모든 생성자를 커버하세요.
-- match on data constructors
data Color = Red | Green | Blue
toString :: Color -> String
toString Red = "red"
toString Green = "green"
toString Blue = "blue"
-- match on Maybe
fromMaybe :: a -> Maybe a -> a
fromMaybe d Nothing = d
fromMaybe _ (Just x) = xWhere / Let
where 절
where는 함수 정의의 하단에 있습니다
-- '|' tests boolean conditions in order
bmiTell :: Double -> String
bmiTell bmi
| bmi <= 18.5 = "underweight"
| bmi <= 25.0 = "normal"
| bmi <= 30.0 = "overweight"
| otherwise = "obese"
> bmiTell 22.0
"normal"let-in 표현식
let-in은 표현식이며, 어디서나 사용 가능합니다
-- otherwise is just True
otherwise :: Bool
otherwise = True
-- a signum implementation
signum' :: Int -> Int
signum' n
| n < 0 = -1
| n == 0 = 0
| otherwise = 1do 블록에서 let
do 블록의 let은 in이 필요 없습니다
-- multiple parameters
max' :: Int -> Int -> Int
max' a b
| a > b = a
| otherwise = b
-- shared helpers via where
bmiTell :: Double -> Double -> String
bmiTell w h
| bmi <= 18.5 = "underweight"
| bmi <= 25.0 = "normal"
| otherwise = "overweight"
where bmi = w / h^2리스트 컴프리헨션에서 let
let은 리스트 컴프리헨션에서 사용할 수 있습니다
-- pattern matching: fixed values/structure
factorial 0 = 1
factorial n = n * factorial (n-1)
-- guards: ranges and conditions
clamp :: Int -> Int -> Int -> Int
clamp lo hi x
| x < lo = lo
| x > hi = hi
| otherwise = xif-then-else
Haskell에서 'if'는 항상 값을 반환하는 표현식입니다 — 양쪽 분기가 모두 필요합니다. 다방향 분기에는 중첩 if-then-else보다 가드가 깔끔합니다. if-then-else는 단순한 이분 선택에 어울립니다.
-- 'if' is an expression that returns a value
abs' :: Int -> Int
abs' n = if n < 0 then -n else n
-- nested ifs (prefer guards for readability)
grade :: Int -> Char
grade n =
if n >= 90 then 'A'
else if n >= 80 then 'B'
else if n >= 70 then 'C'
else 'F'리스트
리스트 기본
리스트는 같은 타입 요소의 연결 리스트입니다
-- where: definitions at the bottom, scoped to a function
area :: Double -> Double -> Double
area w h = w * h_adj
where
h_adj = h * 0.9 -- adjust height
scale = 0.9 -- a helper
-- definitions can refer to each other
f x = a + b
where a = x * 2
b = a + 1 -- refers to a범위 리스트
스텝과 무한 리스트를 지원합니다
-- let <bindings> in <expr>
cylinder :: Double -> Double -> Double
cylinder r h =
let side = 2 * pi * r * h
top = pi * r^2
in side + 2 * top
-- scoped to the expression only
> let z = 5 in z * z
25
-- z is not in scope here리스트 연산
기본 리스트 연산 함수
-- in do, 'let' needs no 'in'
main = do
let x = 5
y = 10
putStrLn $ "sum = " ++ show (x + y)
-- in a list comprehension, no 'in'
> [x*y | x <- [1..3], let y = x+1]
[2, 6, 12]리스트 연결
++는 연결, :는 head에 추가합니다