✏️ 강의 필기

정나영·2022년 10월 10일
0

🔑 How Do I Get Anything Done?

1. Conditionals (조건문)

//java
int price = product.equals("milk") ? 1 : 2;
#python
price = 1 if product == "milk" else 2
//haskell
price = if product == "milk" then 1 else 2
//then, else 생략 불가

📎 Functions Returning Bool

❗️ not-equals: /= ❗️

ghci> "foo" == "bar"
False
ghci> 5.0 <= 7.2
True
ghci> 1 == 1
True
ghci> 2 /= 3
True
ghci> "bike" /= "bike"
False

example)

ghci> :{
ghci| checkPassword password = if password == "swordfish"
ghci|                          then "You're in."
ghci|                          else "ACCESS DENIED!" 
ghci| :}
ghci> :type checkPassword
checkPassword :: String -> String
ghci> checkPassword "Hello"
"ACCESS DENIED!"
ghci> checkPassword "swordfish"
"You're in."
ghci> absolute n = if n < 0 then -n else n
ghci> absoluteValue n = if n < 0 then -n else n
ghci> absoluteValue 123
123
ghci> absoluteValue (-123)
123
ghci> :{
ghci| login user password = if user == "unicon73"
ghci|                       then if password == "f4bulous!"
ghci|                            then "unicon73 logged in"
ghci|                            else "wrong password"
ghci|                       else "unknown user"
ghci| :}
ghci> :type login
login :: String -> String -> String
ghci> login "Hello" "mypassword"
"unknown user"
ghci> login "unicon73" "mypassword"
"wrong password"
ghci> login "unicon73" "f4bulous!"
"unicon73 logged in"

2. Local Definitions (지역변수)

1) where

circleArea :: Double -> Double
circleArea r = pi * rsquare
	where pi = 3.1415926
 	      rsquare = r * r

2) let ... in

circleArea r = let pi = 3.1415926
				   rsquare = r * r
               in pi * rsquare

💡 Local definitions can also be functions

ghci> :{
ghci| circleArea r = pi * square r
ghci|     where pi = 3.1415926
ghci|           square x = x * x
ghci| :}
ghci> circleArea 5
78.539815
ghci> :{
ghci| circleArea r = let pi = 3.1415926
ghci|                    square x = x * x
ghci|                in pi * square r
ghci| :}
ghci> circleArea 5
78.539815

3. Immutability

:변수의 값을 변경할 수 없다

increment x = let x = x + 1
			  in x
compute x = let a = x + 1
		 	    a = a * 2
            in a
error:
	Conflicting definitions for 'a'
  • just 변수의 이름을 가리는 것은 가능
ghci> :{
ghci| x :: Int
ghci| x = 5
ghci| 
ghci| f :: Int -> Int
ghci| f x = 2 * x
ghci| 
ghci| g :: Int -> Int
ghci| g y = x where x = 6
ghci| 
ghci| h :: Int -> Int
ghci| h x = x where x = 3
ghci| :}
ghci> f 1
2
ghci> g 1
6
ghci> h 1
3
ghci> f x
10
ghci> g x
6
ghci> h x
3

4. Pattern Matching

ghci> :{
ghci| greet :: String -> String -> String
ghci| greet "Finland" name = "Hei, " ++ name
ghci| greet "Italy" name = "Ciao, " ++ name
ghci| greet "England" name = "How do you do, " ++ name
ghci| greet _ name = "Hello, " ++ name
ghci| :}
ghci> greet "Finland" "Pekka"
"Hei, Pekka"
ghci> greet "England" "Bob"
"How do you do, Bob"
ghci> greet "Italy" "Maria"
"Ciao, Maria"
ghci> greet "Greenland" "Jan"
"Hello, Jan"

💡참고
가장 첫 등식부터 매칭
_ 같은 special pattern은 가장 뒤에!

ghci> :{
ghci| brokenGreet _ name = "Hello, " ++ name
ghci| brekenGrret "Finland" name = "Hei, " ++ name
ghci| :}
ghci> brokenGreet "Finland" "Varpu"
"Hello, Varpu"
ghci> brokenGreet "Sweden" "Ole"
"Hello, Ole"
ghci> :{
ghci| describe :: Integer -> String
ghci| describe 0 = "zero"
ghci| describe 1 = "one"
ghci| describe 2 = "an even prime"
ghci| describe n = "the number " ++ show n
ghci| :}
ghci> describe 0
"zero"
ghci> describe 2
"an even prime"
ghci> describe 7
"the number 7"

🟰

describe n = if n==0 then "zero"
             else if n==1 then "one"
             else if n==2 then "an even prime"
             else "the number " ++ show n

📌 show 함수
: a 타입의 값을 받아 String으로 바꾸는 함수 (type class)
❗️ 함수에 적용할 수는 없음

ghci> :type show
show :: Show a => a -> String
ghci> show 3.14
"3.14"
ghci> show 7
"7"
ghci> show 'a'
"'a'"

💡 참고 (주석)
1) --
2) {- ... -} : 여러 라인의 주석

ghci> :{
ghci| login :: String -> String -> String
ghci| login "unicon73" "f4bulous!" = "unicon73 loggen in"
ghci| login "unicon73" _ = "wrong password"
ghci| login _ _ = "unknown user"
ghci| :}

🟰

login id = if id == "unicon73"
		   then if pw == "f4bulous!" then "unicon73 logged in"
                else "wrong password"
           else "unknown user"

5. Recursion (재귀)

ghci> :{
ghci| factorial :: Int -> Int
ghci| factorial 1 = 1
ghci| factorial n = n * factorial (n-1)
ghci| :}
ghci> factorial 5
120
ghci> factorial 1
1
ghci> :{
ghci| squareSum 1 = 1
ghci| squareSum n = n^2 + squareSum(n-1)
ghci| :}
ghci> squareSum 1
1
ghci> squareSum 5
55
ghci> :{
ghci| fibonacci 1= 1
ghci| :}
ghci> :{
ghci| fibonacci 1 = 1
ghci| fibonacci 2 = 1
ghci| fibonacci n = fibonacci (n-2) + fibonacci (n-1)
ghci| :}
ghci> fibonacci 1
1
ghci> fibonacci 2
1
ghci> fibonacci 3
2
ghci> fibonacci 4
3
ghci> fibonacci 5
5
ghci> fibonacci 6
8
ghci> fibonacci 7
13

🔑 All Together

-- Collatz.hs

module Collatz where

-- one sterp of the Collatz sequence
step :: Integer -> Integer
step x = if even x then down else up
    where down = div x 2
          up = 3 * x + 1

-- collatz x computes how many steps it takes for the Collatz sequence
-- to reach 1 when starting from x
collatz :: Integer -> Integer
collatz 1 = 0
collatz x = 1 + collatz(step x)

-- longest finds the number with the longest Collatz sequence for initial values
-- between 0 and upperBound
longest :: Integer -> Integer
longest upperBound = longest' 0 0 upperBound

--정보 keep을 위해서는 인자의 개수가 하나여서는 안된다.
--longest ' 으로 재귀를 돌려서 반복
-- helper function for longest
longest' :: Integer -> Integer -> Integer -> Integer
-- end of recursion, return longest length found
longest' number _ 0 = number
-- recursion step: check if n has a longer Collatz sequence than the current known longest
longest' number maxlength n = if length > maxlength
              then longest' n length (n-1)
              else longest' number maxlength (n-1)
    where length = collatz n
-- step 수행 개수 세기
ghci> f x = x : f (step x)
ghci> takeWhile (/=1) (f 3)
[3,10,5,16,8,4,2]
ghci> take 20 (f 9)
[9,28,14,7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]
-- longest 수행
-- 1부터 10 중에서 collatz 수행 길이가 가장 긴 
ghci>  [ collatz x| x <- [1..10]]
[0,1,7,2,5,8,16,3,19,6]
ghci>  [ (x, collatz x)| x <- [1..10]]
[(1,0),(2,1),(3,7),(4,2),(5,5),(6,8),(7,16),(8,3),(9,19),(10,6)]
ghci> step 3
10
ghci> step 10
5
ghci> step 5
16
ghci> collatz 3
7
ghci> longest 10 
9
ghci> longest 100
97
ghci> collatz 9
19
ghci> collatz 97
118

🔑 Indentation (들여쓰기)

ghci> i x = let y = x+x+x+x+x+x in div y 5

ghci> :{
ghci| j x = let y = x+x+x
ghci|               +x+x+x
ghci|       in div y 5
ghci| :}
ghci> :type j
j :: Integral p => p -> p

ghci> :{
ghci| k = a + b
ghci|   where a = 1
ghci|         b = 1
ghci| :}

ghci> :{
ghci| l = a + b
ghci|   where
ghci|     a = 1
ghci|     b = 1
ghci| :}
ghci> :type l
l :: Num a => a

0개의 댓글