프로그래밍 Programming
Functional Programming with Haskell - fromTo
2018. 4. 20.정수의 범위로 된 리스트를 생성하는 다음 함수를 보자.123456789 Prelude Data.Char> let fromTo first last = [first..last]fromTo :: Enum t => t -> t -> [t] Prelude Data.Char> fromTo 10 15[10,11,12,13,14,15]it :: (Enum t, Num t) => [t]Prelude Data.Char> Colored by Color Scriptercs cons 연산자를 사용하여 fromTo 의 재귀적 버전을 작성해보자.12fromTo first last | first > last = [] | otherwise = first : fromTo (first+1) lastcs 대체와 다시쓰기를 통해 fromTo..
Functional Programming with Haskell - "cons" lists
2018. 4. 20.대부분의 functional languages 와 마찬가지로, 하스켈의 리스트는 "cons" 리스트이다. "cons" 리스트는 2개의 부분으로 구성된다. head: a valuetail: a list of values (빈 리스트도 가능): ("cons") 연산은 값과 동일한 타입의 값으로 구성된 리스트(혹은 빈 리스트)로부터 새로운 리스트를 생성한다.12345678 Prelude> 5 : [10,20,30][5,10,20,30]it :: Num a => [a] Prelude> :type (:)(:) :: a -> [a] -> [a] cs cons (:) 연산은 값과 리스트로부터 새로운 리스트를 만든다.1234567891011121314151617181920212223242526272829 Prelude..
Functional Programming with Haskell - Strings are [Char]
2018. 4. 19.하스켈에서 문자열은 단순히 문자의 리스트이다. 1234567891011121314151617 Prelude> "testing""testing"it :: [Char] Prelude> ['a'..'z']"abcdefghijklmnopqrstuvwxyz"it :: [Char] Prelude> ["ust","a","test"]["ust","a","test"]it :: [[Char]] Prelude> ["just","a","test"]["just","a","test"]it :: [[Char]] cs 리스트에서 사용가능한 함수는 모두 문자열에서도 사용할 수 있다.123456789101112 Prelude> let asciiLets = ['A'..'Z'] ++ ['a'..'z']asciiLets :: [Char] P..
Functional Programming with Haskell - Comparing lists, Lists of Lists
2018. 4. 19.Comparing lists하스켈 리스트는 값이고, 값으로 비교가능하다. 아래를 보자.12345678910 Prelude> [3,4] == [1+2,2*2]True Prelude> [3] ++ [] ++ [4] == [3,4]True Prelude> tail (tail [3,4,5,6]) == [last [4,5]] ++ [6]True Colored by Color Scriptercs리스트의 비교는 사전 편찬상의 순서를 따른다. 대응되는 원소간의 비교는 서로 다른 것이 나타날 때까지 계속되고, 서로 다른 원소를 비교결과가 그 리스트의 비교 결과가 된다. 123 Prelude> [1,2,3] [1,2,3] [1,2,3] [1,2,3] > [1,2]True Prelude> [1..] let x = [[1],..
Functional Programming with Haskell - Lists basics
2018. 4. 17.하스켈에서 리스트는 같은 타입을 가진 연속된 값을 의미한다. 아래는 리스트는 만드는 간단한 방법으로, 각각의 타입에 주목해서 살펴보자.12345678910111213141516171819 *Main> [7,3,8][7,3,8]it :: Num t => [t] *Main> [1,3,10,4,9.7][1.0,3.0,10.0,4.0,9.7]it :: Fractional t => [t] *Main> ['x', 10] :79:7: No instance for (Num Char) arising from the literal ‘10’ In the expression: 10 In the expression: ['x', 10] In an equation for ‘it’: it = ['x', 10] Colored by C..
Functional Programming with Haskell - Recursion
2018. 4. 17.함수 자신을 직접 또는 간접적으로 호출하는 함수를 재귀함수라고 한다. 정수의 팩토리얼(N!) 을 계산하는 것이 전형적인 재귀의 예시이다. 그럼 이를 하스켈로 작성해보자. 그리고 그 타입이 무엇인지 알아보자. 12factorial n | n == 0 = 1 | otherwise = n * factorial (n-1)cs 1234567891011121314 *Main> :load factorial[1 of 1] Compiling Main ( factorial.hs, interpreted )Ok, modules loaded: Main. *Main> :type factorialfactorial :: (Eq a, Num a) => a -> a *Main> factorial 4081591528324789773434..
Functional Programming with Haskell - Haskell's if-else
2018. 4. 16.하스켈 if-else 의 간단한 예를 보자. 123456 *Main> if 1 a*Main> cs 그럼, 자바에서 어떤가? 자바의 if-else 는 구문이다. 하스켈 if-else 와 유사한 것은 자바의 조건연산자이다. 아래는 자바 조건(삼항) 연산자의 예로, 값의 도출이 필요할 때 사용할 수 있는 expression 이다.11 if 1 a*Main>*Main> :type if 1 *Main> :type if 1 *Main> if 1
Functional Programming with Haskell -Guards
2018. 4. 13.현재까지 살펴본 함수를 정의하는 일반적인 형식은 다음과 같다. let name param1 param2 ... paramN = expression 주어진 3개의 값의 최소값을 계산하는 min3 라는 함수를 정의해보자. Prelude는 min 이라는 함수를 가지고 있다. 이를 이용해서 작성해보자.1234567 Prelude> let min3 a b c = min a (min b c)min3 :: Ord a => a -> a -> a -> a Prelude> min3 5 2 102it :: (Num a, Ord a) => acs Guards아래 함수는 3가지 경우를 대비하여 가드를 사용한 예이다. 123sign x | x smaller 7 107it :: (Num a, Ord a) => a*Main> sma..
Functional Programming with Haskell - Function/operator equivalence CSC 372
2018. 3. 31.하스켈 연산자는 중위폼이 적용된 함수라고 볼 수 있다. 연산자에 대해서 더 알고 싶으면 아래와 같이 :info 를 사용한다.123456 Prelude> :info (^)(^) :: (Num a, Integral b) => a -> b -> a -- Defined in ‘GHC.Real’infixr 8 ^Prelude> Colored by Color Scriptercs여기서 (Num a, Integral b) => a -> b -> a 가 의미하는 것은 첫 번째 피연산자는 number 이고 두 번째는 integer 여야 한다는 것이다. infixr 8 의 의미는 right-associative 이고, 8의 우선순위를 갖는다는 의미이다. 하스켈 연산자의 우선순위에 대해서는 아래를 참조한다.Precedence..
Functional Programming with Haskell -Specifying a function's type and indentation
2018. 3. 31.Key points: • Integer -> Char -> Char 와 같은 타입을 가진 함수의 경우, Integer 과 Char 라는 2개의 인수를 갖고, Char 를 결과로 반환한다. • f x y z 와 같은 함수 콜이 의미하는 것은 ((f x) y) z 이고 개념적으로는 2개의 이름없는 임시함수가 생성된다. • 요구되는 것보다 적은 인수로 함수를 호출하면 partial application 이 생성된다. Specifying a function's type 함수의 정의와 함께 함수의 타입을 특정하는 것이 일반적이다. Continuation with indentation 하스켈 소스 파일은 연속되는 선언의 모음이나 마찬가지다. 아래 2개의 선언을 포함한 파일을 살펴보자. 12345 (blackbria..
Functional Programming with Haskell - Functions with multiple arguments
2018. 3. 30.2개의 인수를 가지고 합을 구하는 함수가 있다.1234567Prelude> let add x y = x + y ::IntegerPrelude> add 3 58 Prelude> :type addadd :: Integer -> Integer -> Integer Colored by Color Scriptercs -> 연산자는 right-associative 이므로, 위의 의미는 아래와 같다.add :: Integer -> (Integer -> Integer) 이것은 무슨 의미인가? negate 함수를 다시 떠올려보자. 12Prelude> let neg x = -x ::Integerneg :: Integer -> Integercs여기서 다시 add 를 등장시키자. 우선 순위를 보여주기 위해서 괄호를 이용하자.1..
Functional Programming with Haskell - Loading functions from a file
2018. 3. 30.함수의 정의를 파일에 넣어서 사용할 수 있다. 이 경우 let 은 불필요하다. simple.hs 파일에 아래와 같이 4개의 함수를 입력하고 저장하자. .hs 확장자는 반드시 필요하다. simple.hs1234double x = x * x ::Integerneg x = -x::IntegerisPositive x = x > (0::Integer)toCelsius temp = (tem[ - 32) * 5/(9::Double)cs 다음과 같이 커맨드라인에서 해당 파일의 내용을 확인해보자. 12345(blackbriar) root@gcloudx:~/blackbriar# cat simple.hsdouble x = x * x ::Integerneg x = -x::IntegerisPositive x = x > (0::..
Functional Programming with Haskell - Simple functions
2018. 3. 30.그럼 간단한 함수를 작성해보자.1234567891011121314151617181920Prelude> let double x = x * 2double :: Num a => a -> a Prelude> :t doubledouble :: Num a => a -> a Prelude>Prelude> double 510it :: Num a => a Prelude> double 2.75.4it :: Fractional a => a Prelude> double (double (double 111111111))888888888it :: Num a => aPrelude> Colored by Color Scriptercs좀 더 예를 살펴보자.12345678Prelude> let neg x = -xneg :: Num a =..
Functional Programming with Haskell - Type classes
2018. 3. 30.Type classes하스켈 타입의 예를 들어보면, Bool, Char, 그리고 Integer 등이 있다. 그리고 하스켈은 type classes 도 가지고 있다. 타입 클래스는 해당 타입이 그 타입 클래스의 멤버이기 위해 그 타입이 갖추어야하는 작동을 특정한다. Num 은 Prelude 에서 정의된 많은 타입 클래스 중의 하나이다. :info Num 을 통해 살펴보면, 타입이 Num 이 되기 위해서는 덧셈, 뺄셈, 곱셈, 그리고 4가지 기능(negate, abs, signNum, fromInteger)을 지원해야 한다. 그리고 Prelude 는 Num 타입 클래스의 4가지 인스턴스를 정의하고 있는데, Int(word-size), Integer (unlimited size), Float 그리고 Doubl..
하스켈 모듈 언로딩 How to go back to prelude> in ghci
2018. 3. 27.ghci 에서 특정 모듈을 로딩한 후 다시 해제할 때는 다음과 같이 :m 명령어를 사용하면, 로딩되었던 임의의 모든 모듈을 언로드시킬 수 있다. 123Prelude> :m Data.CharPrelude Data.Char> :mPrelude>cs 또는 다음과 같이 :m - 구문으로도 언로드 할 수 있다. 123Prelude> :m NumericPrelude Numeric> :m -NumericPrelude>cs https://stackoverflow.com/questions/9305366/how-to-go-back-to-prelude-in-ghci
Functional Programming with Haskell - Function types
2018. 3. 24.하스켈의 Data.Char 모듈에는 문자를 다루는 다수의 함수가 포함되어 있다. 먼저 :m Data.Char 과 같이 해당 모듈을 로딩한다.1234567891011121314151617Prelude> :m Data.Char Prelude Data.Char> isLower 'b'Trueit :: Bool Prelude Data.Char> toUpper 'a''A'it :: Char Prelude Data.Char> ord 'A'65it :: Int Prelude Data.Char> chr 66'B'it :: Charcs아래와 같이 모듈명을 붙여서(with a qualified name) 참조할 수도 있다.123Prelude> Data.Char.ord 'G'71it :: Intcs함수의 타입을 알아보기 위해..
Functional Programming with Haskell - Calling functions
2018. 3. 24.하스켈에서 juxtaposition 는 함수호출을 나타낸다. 아래와 같은 함수들은 이미 ghci 가 시작될 때 로딩되는 Haskell "Prelude" 에 정의되어 있다. 아래 링크에서 추가적인 함수들을 살펴볼 수 있다.http://zvon.org/other/haskell/Outputprelude/index.html 123456789101112131415Prelude> negate 3-3it :: Num a => a Prelude> even 5Falseit :: Bool Prelude> pred 'C''B'it :: Char Prelude> signum 21it :: Num a => acsnegate change the sign of the number.even returns True if the int..
Functional Programming with Haskell - 패러다임
2018. 3. 24.1962년 토마스 쿤의 저서 에서는 패러다임을 아래와 같은 과학적 성과로 기술하고 있다. 그리고 그러한 성과의 예로, 뉴튼의 프린키피아, 라부아지에의 화학 등을 들고 있다. • "...sufficiently unprecedented to attract an enduring group of adherents away from competing modes of scientific activity."• "...sufficiently open-ended to leave all sorts of problems for the redefined group of practitioners to resolve." 패러다임은 문제를 이해하고 푸는데 필요한 개념적 프레임워크를 제공해준다. 그리고 패러다임은 문제를 해결하는데 ..
Functional Programming with Haskell - Interacting with Haskell
2018. 3. 22.본격적인 내용에 앞서 사용중인 운영체제에 맞게 아래에서 다운로드하여 설치한다.https://www.haskell.org/downloads 설치 후 CMD, BASH 또는 WinGHCi, GHCi 에서 ghci 를 실행한다. 123root@gcloudx:~# ghciGHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for helpPrelude> Colored by Color Scriptercs 표준 프롬프트는 Prelude> 이다. 아래와 같이 프롬프트를 설정할 수도 있다.1234567root@gcloudx:~# ghciGHCi, version 7.10.3: http://www.haskell.org/ghc/ :? for helpPrelude> :set promp..
Haskell_007 Where
2018. 3. 17.Since we repeat the same expression three times, it would be ideal if we could calculate it once, bind it to a name and then use that name instead of the expression. bmiTell :: (RealFloat a) => a -> a -> String bmiTell weight height | bmi
Haskell Operators and other Lexical Notation
2018. 3. 17.Haskell_006 Guards
2018. 3. 17.Guards are a way of testing whether some property of a value (or several of them) are true or false. We're going to make a simple function that berates you differently depending on your BMI.bmiTell :: (RealFloat a) => a -> String bmiTell bmi | bmi
Haskell_005 Pattern matching
2018. 3. 17.1. Pattern matching consists of 1. specifying patterns to which some data should conform2. checking to see if it does 3. deconstructing the data according to those patterns When defining functions, you can define separate function bodies for different patterns. 2. You can pattern match on any data type — numbers, characters, lists, tuples, etc. 3. Order is important when specifying patterns and ..
Haskell_004 Some basic typeclasses - Eq, Ord, Show, Read, Enum, Bounded, and Num
2018. 3. 16.Eq and Ord Eq is used for types that support equality testing. The functions its members implement are == and /=. ghci> 5 == 5 True ghci> 5 /= 5 False ghci> 'a' == 'a' True ghci> "Ho Ho" == "Ho Ho" True ghci> 3.432 == 3.432 True Ord is for types that have an ordering. Ord covers all the standard comparing functions such as >, = and :t (>) (>) :: (Ord a) => a -> a -> Bool The compare function tak..
Haskell Type, Typeclass, and Type variables
2018. 3. 16.Type A kind of label that every expression has. Category of things that expression fits. :t examine the types of some expressions :: is read as "has type of" The parameters are separated with -> There's no special distinction between the parameters and the return type. The return type is the last item in the declaration. Type Variable12Prelude> :t headhead :: [a] -> acs What is this a? It's actu..
Haskell_ 003 Typeclass
2018. 3. 15.A typeclass is a sort of interface that defines some behavior. If a type is a part of a typeclass, that means that it supports and implements the behavior the typeclass describes. Type signature of the == functionghci> :t (==) (==) :: (Eq a) => a -> a -> Bool The equality operator, == is a function. +, *, -, / and pretty much are all operators. If a function is comprised only of special characte..
Haskell_ 002 Type variables
2018. 3. 9.Type of the head function head takes a list of any type and returns the first element. The type declaration of head states that it takes a list of any type and returns one element of that type.ghci> :t head head :: [a] -> a What is this a? Types are written in capital case, so it can't exactly be a type. It's actually a type variable. That means that a can be of any type. polymorphic functions :..
Haskell_ 001 Type and typeclass
2018. 3. 5.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 (Tru..
하스켈 패키지 삭제하기 How to uninstall a Haskell package installed with stack?
2018. 2. 6.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 (blackbriar) root@gcloudx:~/blackbriar/blackbriar# stack --helpstack - The Haskell Tool Stack Usage: stack [--help] [--version] [--numeric-version] [--hpack-num..
cabal install 사용방법 (1) How to cabal install (1)
2018. 2. 6.cabal은 하스켈로 작성된 소프트웨어를 다운로드받고 빌딩하는 명령프로그램이다. 이를 통해 Hackage repository 에 존재하는 모든 패키지를 다운받아 설치할 수 있다. 가끔 알수없는 오류를 일으키기도 하는데 본 포스팅읉 통해 올바른 cabal 패키지 설치방법을 알아보자. cabal, Cabal, cabal-install혼동을 피하기 위해 먼저 Cabal wiki page 의 설명을 먼저 보자."Cabal 은 패키지 및 빌드 시스템이다. Cabal 은 단지 패키지의 생성과 그 컨텐츠의 빌딩에만 관여한다. 패키지를 관리하지는 않는다. Cabal-Install 은 카발 패키지를 설치한다. 그것은 빌드시스템인 Cabal 과는 구분된다. 이러한 점들은 종종 새로운 사용자들에게 혼동을 일으킨다. 게다가 ..