프로그래밍 Programming
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 과는 구분된다. 이러한 점들은 종종 새로운 사용자들에게 혼동을 일으킨다. 게다가 ..
Haskell Yesod의 템플릿 언어 세익스피어를 활용하여 웹페이지 만들기 (2)
2018. 2. 3.Haskell Yesod의 템플릿 언어 세익스피어를 활용하여 웹페이지 만들기 (2) 이전 포스팅에서는 헤더와 푸터 영역의 작성에 대해서 알아봤습니다. 현시점에서 샘플사이트의 모습은 대략 이런 느낌일 것입니다.이번 회차에서는 아래의 부분을 완성해보겠습니다.슬라이드쇼메인 컨텐츠템플릿 파일에 대해서 templates/default-layout-wrapper이 파일에는head태그에 포함된 meta태그와 title태그 및 닫힌 body 태그의 앞에 배치된 스크립트 등을 기술합니다. 사이트 전체의 레이아웃 헤더, 푸터, 사이드바 등의 구조)는 기술하지 않고, 해당 정보는 차후에 언급할 templates/default-layout 에 기술합니다.templates/default-layout이 파일에서는 사이트의 레이아..
Haskell Yesod의 템플릿 언어 세익스피어를 활용하여 웹페이지 만들기 (1)
2018. 2. 1.Haskell Yesod의 템플릿 언어 세익스피어를 활용하여 웹페이지 만들기 (1) 앞으로 2개의 포스팅을 통해 Yesod로 웹페이지를 구현해보겠습니다.먼저, Yesod로 Web 페이지를 구현하기 위한 템플릿 언어에는 다음이 있습니다.Hamlet들어쓰기를 활용한 네스트 표현Cassius (Lucius)Lucius 는 CSS 의 슈퍼세트로、CSS 기술Lucius 는 {} 를 통해 네스트 표현Julius들어쓰기로 네스트를 표현이상을 합쳐서 Shakespeare라고 부르고, 각각은 HTML, CSS, Javascript 에 대응합니다. HTML 이 Hamlet 에, Cassius (Lucius) 이 CSS 에, Javascript 에 Julius 가 대응하는 등 첫 글자가 동일한 것은 뭐 우연일 것입니다. W..
Yesod의 위젯에 대해서 (1)
2018. 1. 27.Widget 이란?Yesod의 경우 위젯의 역할은 HTML, CSS, Javascript 등의 컴포넌트를 적절히 하나의 HTML로 정리하기 위한 통일된 표현을 부여하기 위한 것입니다. 예를 들면, Web 페이지를 기술하는 실제에서는 아래의 형식적인 관습을 따르는 편이 좋습니다.CSS는 페이지의 head 부분에 기술한다Javascript은 body의 마지막에 기술한다jQuery 등의 외부 파일을 여러번 회독하지 않음타이틀태그는 한 번 출현위젯 컴포넌트컴포넌트의 종류실제 태그Yesod에서 취급하기 위한 함수 또는 템플릿 언어타이틀 ... setTitle외부의 스타일시트addStylesheet계열외부의 JavascriptaddScript계열CSS 코드Cassius or LuciusJavascript 코드Jul..
하스켈 익스텐션 사용법 How to Enable Extensions
2018. 1. 26.GHC extension은 적어도 3가지 방법으로 단독 또는 결합하여 사용가능합니다. ExtensionName 이라고 불리는 가상의 extension에 대해 알아봅니다. LANGUAGE Pragma개별 파일에 대해서는 파일 상단에 {-# LANGUAGE ExtensionName #-} 라는 형식으로 사용이 가능합니다 (module 헤더 이전, 또는 첫 번째 import 이전 및 module 헤더가 없다면 definition 이전에 위치). 여러 개의 LANGUAGE pragmas 를 사용함으로써 여러개의 extension 도 사용가능합니다. 예를 들면, ScopedTypeVariables, LiberalTypeSynonyms, 와 MultiWayIf 라는 3개의 extension 을 사용하려면 다음의 3..
하스켈 Yesod 튜토리얼 - 페이지 추가하기 Minimal echo application
2018. 1. 19.아래 4개의 파일과 디렉토리에 주안점을 두고 본 튜토리얼을 진행한다. 현재 구성은 다음 이미지와 같다.config/routesHandler/templates/config/modelsconfig/routes 는 URL → Code 로 매핑하는 설정을 하는 파일이다. config/models 은 데이터베이스 테이블 같은 지속성 객체에 대한 설정을 다룬다. templates/HTML, js, 그리고 CSS 템플릿 파일을 포함한다.Handler/ 디렉토리는 URL 을 통해 접근되는 코드를 포함한 파일이 들어있다.Yesod framework의 보안성을 평가하기 위해 아래와 같이 간단한 echo 어플리케이션을 만든다. /echo/[some text]로 접속했을 때 h1 블럭 안에 있는 "some text"를 반환하..
하스켈 Yesod Illegal view pattern: fromPathPiece -> Just dyn_anHx
2018. 1. 19.1234567891011121314151617 blackbriar-0.0.0: build (lib)Preprocessing library blackbriar-0.0.0...[11 of 12] Compiling Handler.Echo ( src/Handler/Echo.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Handler/Echo.o )[12 of 12] Compiling Application ( src/Application.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/build/Application.o ) /src/Application.hs:50:1: error: Illegal view pattern: f..
하스켈 Yesod Echo.hs:6:48: error: parse error on input ‘{’
2018. 1. 19.하스켈 Yesod 페이지를 추가하는 튜토리얼을 진행하는 중 다음과 같이 Echo.hs:6:48: error: parse error on input ‘{’ 을 만나는 경우 다음과 같이 처리한다. src/Echo.hs 123456module Handler.Echo where import Import getEchoR :: String -> Handler HtmlgetEchoR theText = defaultLayout [whamlet|#{theText}|]cs 상기 소스를 rebuild 하면 다음과 같은 에러 발생1234567[11 of 12] Compiling Handler.Echo ( src/Handler/Echo.hs, .stack-work/dist/x86_64-linux/Cabal-1.24.2.0/bu..
하스켈 Starting out - (9) 타입 변수 Type variables
2017. 12. 5.head 함수의 타입이 무엇이라고 생각하는가? head 함수는 리스트를 받아 첫 번째 요소를 반환한다. 지금 확인해보자. Prelude> :t headhead :: [a] -> a여기서 a는 무엇인가? 타입을 뜻하는 것인가? 앞서 타입은 대문자로 쓴다고 말한바 있다. 그러므로 a는 타입이 아니다. 타입이 아니라 타입변수(type variable)이다.a는 어떤 타입이라도 될 수 있다는 의미이다. 다른 언어의 제너릭같은 개념이다. 타입 변수를 가지고 있는 함수는 다형함수(polymorphic functions) 라고 부른다. head 의 타입 선언은 어떤 타입의 리스트를 받아서 그 타입의 한 원소를 반환한다는 말이다. fst 함수를 기억하는가? 페어의 첫 번째 요소를 반환하는 함수이다. 타입을 확인해보자...
하스켈 Starting out - (8) 타입
2017. 12. 5.하스켈은 정적 타입 시스템이다. 모든 표현식의 타입이 컴파일 당시에 이미 알려져있다. 예를 들어 불린 타입을 어떤 숫자로 나눌려고 하면, 컴파일되지 않는다. 프로그램이 충돌하기 전에 컴파일 당시에 이런 오류가 발견되는 것이 좋다. 하스켈의 모든 것은 타입을 가지며, 따라서 컴파일러는 컴파일하기 전에 프로그램에 대해 어느 정도 판단을 할 수 있다. 자바나 파스칼과는 다르게 하스켈은 타입추론(type inference)을 가진다. 만약 숫자를 쓰면, 굳이 하스켈에게 그것이 숫자라고 말할 필요가 없다는 것이다. 하스켈에 있어 타입 시스템을 이해하는 것은 매우 중요하다.타입은 모든 표현식이 가지는 일종의 라벨이다. 표현식이 어떤 카테고리에 속하는지 말해주는 셈이다. 표현식이라는 것은 True 같은 불린이나 "h..
Error haskell: Variable not in scope
2017. 12. 4.다음과 같이 Variable not in scope 에러가 발생하는 경우Prelude> addThree :: Int -> Int -> Int -> Int :89:1: error: Variable not in scope: addThree :: Int -> Int -> Int -> Int 이 경우에는 다음과 같이 멀티플 라인 입력을 해야한다. 아니면 해당 코드를 파일로 저장하여 :load 을 이용하여 로딩할 수도 있다.Prelude> :{Prelude| addThree :: Int -> Int -> Int -> IntPrelude| addThree x y z = x + y + zPrelude| :}Prelude> addThree 3737 383839 393939393939393939781515Prelude>