se

    let boolean3 = not boolean1 && (boolean2 || false)

    printfn "The expression 'not boolean1 && (boolean2 || false)' is %A" boolean3



// ---------------------------------------------------------------
//         문자열
// ---------------------------------------------------------------

module StringManipulation = 

    let string1 = "Hello"
    let string2  = "world"

    /// @를 사용하여 축자 문자열 리터럴을 만듭니다.
    let string3 = @"c:\Program Files\"

    /// 3중 따옴표 문자열 리터럴을 사용하면
    let string4 = """He said "hello world" after you did"""

    let helloWorld = string1 + " " + string2 // 사이에 공백이 있는 두 문자열이 연결됩니다.
    printfn "%s" helloWorld

    /// 결과 문자열 중 하나에서 처음 7개 문자를 가져와서 형성된 문자열
    let substring = helloWorld.[0..6]
    printfn "%s" substring



// ---------------------------------------------------------------
//         튜플(정렬된 값 집합)
// ---------------------------------------------------------------

module Tuples = 

    /// 단순한 정수 튜플
    let tuple1 = (1, 2, 3)

    /// 튜플에 있는 두 값의 순서를 바꾸는 함수입니다.
    /// QuickInfo는 함수가 제네릭 형식을 갖는 것으로 유추됨을 보여 줍니다.
    let swapElems (a, b) = (b, a)

    printfn "The result of swapping (1, 2) is %A" (swapElems (1,2))

    /// 정수, 문자열 및 배정밀도 부동 소수점 수로 구성된 튜플
    let tuple2 = (1, "fred", 3.1415)

    printfn "tuple1: %A    tuple2: %A" tuple1 tuple2
    


// ---------------------------------------------------------------
//         리스트 및 리스트 처리
// ---------------------------------------------------------------

module Lists = 

    let list1 = [ ]            /// 빈 리스트

    let list2 = [ 1; 2; 3 ]    /// 3개의 요소로 구성된 리스트

    let list3 = 42 :: list2    /// 처음에 '42'가 추가된 새 리스트

    let numberList = [ 1 .. 1000 ]  /// 1부터 1000까지의 정수 리스트

    /// 연중 모든 날짜를 포함하는 리스트
    let daysList = 
        [ for month in 1 .. 12 do
              for day in 1 .. System.DateTime.DaysInMonth(2012, month) do 
                  yield System.DateTime(2012, month, day) ]

    /// 체스 보드에서 검은색 칸의 좌표를 가리키는 튜플이 포함된 리스트입니다.
    let blackSquares = 
        [ for i in 0 .. 7 do
              for j in 0 .. 7 do 
                  if (i+j) % 2 = 1 then 
                      yield (i, j) ]

    /// 파이프라인 연산자로 List.map에 인수를 전달하여 numberList의 수를 제곱합니다.    
    let squares = 
        numberList 
        |> List.map (fun x -> x*x) 

    /// 3으로 나눠지는 수의 제곱의 합을 계산합니다.
    let sumOfSquares = 
        numberList
        |> List.filter (fun x -> x % 3 = 0)
        |> List.sumBy (fun x -> x * x)



// ---------------------------------------------------------------
//         클래스
// ---------------------------------------------------------------

module DefiningClasses = 

    /// 이 클래스의 생성자는 dx와 dy라는 두 개의 인수를 사용하며 둘 모두 'float' 타입입니다. 
    type Vector2D(dx : float, dy : float) = 
        /// 개체가 생성될 때 계산된 벡터 길이
        let length = sqrt (dx*dx + dy*dy)

        // 'this'는 개체 자체의 식별자에 대한 이름을 지정합니다.
        // 인스턴스 메서드에서는 멤버 이름 앞에 와야 합니다.
        member this.DX = dx  

        member this.DY = dy

        member this.Length = length

        member this.Scale(k) = Vector2D(k * this.DX, k * this.DY)
    
    /// Vector2D 클래스의 인스턴스
    let vector1 = Vector2D(3.0, 4.0)

    /// 원래 개체를 수정하지 않고 비율이 조정된 새 개체를 가져옵니다. 
    let vector2 = vector1.Scale(10.0)

    printfn "Length of vector1: %f      Length of vector2: %f" vector1.Length vector2.Length



// ---------------------------------------------------------------
//         제네릭 클래스
// ---------------------------------------------------------------

module DefiningGenericClasses = 

    type StateTracker<'T>(initialElement: 'T) = // 'T는 클래스의 타입 매개 변수입니다.

        /// 목록에 상태 저장
        let mutable states = [ initialElement ]

        /// 상태 리스트에 새 요소를 추가합니다.
        member this.UpdateState newState = 
            states <- newState :: states  // '<-' 연산자를 사용하여 값을 변경합니다.

        /// 기록 상태의 전체 리스트를 가져옵니다.
        member this.History = states

        /// 최신 상태를 가져옵니다.
        member this.Current = states.Head

    /// 상태 추적기 클래스의 'int' 인스턴스입니다. 타입 매개 변수는 유추됩니다.
    let tracker = StateTracker 10

    // 상태를 추가합니다.
    tracker.UpdateState 17



// ---------------------------------------------------------------
//         인터페이스 구현
// ---------------------------------------------------------------

/// IDisposable을 구현하는 타입입니다.
type ReadFile() =

    let file = new System.IO.StreamReader("readme.txt")

    member this.ReadLine() = file.ReadLine()

    // 이 클래스의 IDisposable 멤버 구현입니다.
    interface System.IDisposable with    
        member this.Dispose() = file.Close()



// ---------------------------------------------------------------
//         배열
// ---------------------------------------------------------------

module Arrays = 

    /// 빈 배열
    let array1 = [| |]

    let array2 = [| "hello"; "world"; "and"; "hello"; "world"; "again" |]

    let array3 = [| 1 .. 1000 |]

    /// 단어 "hello" 및 "world"만 포함하는 배열입니다.
    let array4 = [| for word in array2 do
                        if word.Contains("l") then 
                            yield word |]

    /// 0부터 2000까지의 짝수가 포함되고 인덱스로 초기화된 배열입니다.
    let evenNumbers = Array.init 1001 (fun n -> n * 2) 

    /// 조각화 표기법을 사용하여 추출된 하위 배열
    let evenNumbersSlice = evenNumbers.[0..500]

    for word in array4 do 
        printfn "word: %s" word

    // 왼쪽 화살표 할당 연산자를 사용하여 배열 요소를 수정합니다.
    array2.[1] <- "WORLD!"

    /// 'h'로 시작하는 단어의 길이 합을 계산합니다.
    let sumOfLengthsOfWords = 
        array2
        |> Array.filter (fun x -> x.StartsWith "h")
        |> Array.sumBy (fun x -> x.Length)



// ---------------------------------------------------------------
//         시퀀스
// ---------------------------------------------------------------

module Sequences = 
    // 시퀀스는 요청 시 계산되며 반복될 때마다 다시 계산됩니다. 
    // F# 시퀀스는 System.Collections.Generic.IEnumerable<'T>의 인스턴스이므로,
    // Lists와 Arrays에도 Seq 함수를 적용할 수 있습니다.

    /// 빈 시퀀스
    let seq1 = Seq.empty

    let seq2 = seq { yield "hello"; yield "world"; yield "and"; yield "hello"; yield "world"; yield "again" }

    let numbersSeq = seq { 1 .. 1000 }

    /// "hello" 및 "world"라는 단어만 포함된 다른 배열입니다.
    let seq3 = 
        seq { for word in seq2 do
                  if word.Contains("l") then 
                      yield word }

    let evenNumbers = Seq.init 1001 (fun n -> n * 2) 

    let rnd = System.Random()

    /// 임의 행로인 무한 시퀀스입니다.
    //  IEnumerable.SelectMany와 마찬가지로, yield!를 사용하여 하위 시퀀스의 각 요소를 반환합니다.
    let rec randomWalk x =
        seq { yield x
              yield! randomWalk (x + rnd.NextDouble() - 0.5) }

    let first100ValuesOfRandomWalk = 
        randomWalk 5.0 
        |> Seq.truncate 100
        |> Seq.toList



// ---------------------------------------------------------------
//         재귀 함수
// ---------------------------------------------------------------

module RecursiveFunctions  = 
              
    /// 정수의 계승을 계산합니다. 'let rec'를 사용하여 재귀 함수를 정의합니다.
    let rec factorial n = 
        if n = 0 then 1 else n * factorial (n-1)

    /// 두 정수의 최대 공약수를 계산합니다. 
    //  모든 재귀 호출은 마무리 호출이므로 컴파일러에서는 함수를 루프로 전환합니다.
    //  루프는 성능을 향상시키고 메모리 소비량을 줄여 줍니다.
    let rec greatestCommonFactor a b =                       
        if a = 0 then b
        elif a < b then greatestCommonFactor a (b - a)           
        else greatestCommonFactor (a - b) b

    /// 재귀를 사용하여 정수 리스트의 합을 계산합니다.
    let rec sumList xs =
        match xs with
        | []    -> 0
        | y::ys -> y + sumList ys

    /// 도우미 함수와 결과 누적기를 사용하여 함수를 마무리 재귀 함수로 만듭니다.
    let rec private sumListTailRecHelper accumulator xs =
        match xs with
        | []    -> accumulator
        | y::ys -> sumListTailRecHelper (accumulator+y) ys

    let sumListTailRecursive xs = sumListTailRecHelper 0 xs



// ---------------------------------------------------------------
//         레코드 타입
// ---------------------------------------------------------------

module RecordTypes = 

    // 레코드 타입을 정의합니다.
    type ContactCard = 
        { Name     : string;
          Phone    : string;
          Verified : bool }
              
    let contact1 = { Name = "Alf" ; Phone = "(206) 555-0157" ; Verified = false }

    // contact1의 복사본이지만 'Phone' 및 'Verified' 
    // 필드의 값은 다른 새 레코드를 만듭니다.
    let contact2 = { contact1 with Phone = "(206) 555-0112"; Verified = true }

    /// 'ContactCard' 개체를 문자열로 변환합니다.
    let showCard c = 
        c.Name + " Phone: " + c.Phone + (if not c.Verified then " (unverified)" else "")
        


// ---------------------------------------------------------------
//         공용 구조체 타입
// ---------------------------------------------------------------

module UnionTypes = 

    /// 플레잉 카드의 짝패를 나타냅니다.
    type Suit = 
        | Hearts 
        | Clubs 
        | Diamonds 
        | Spades

    /// 플레잉 카드의 순위를 나타냅니다.
    type Rank = 
        /// 카드 2부터 10까지의 순위를 나타냅니다.
        | Value of int
        | Ace
        | King
        | Queen
        | Jack
        static member GetAllRanks() = 
            [ yield Ace
              for i in 2 .. 10 do yield Value i
              yield Jack
              yield Queen
              yield King ]
                                   
    type Card =  { Suit: Suit; Rank: Rank }
              
    /// 데크에 있는 모든 카드를 나타내는 리스트를 반환합니다.
    let fullDeck = 
        [ for suit in [ Hearts; Diamonds; Clubs; Spades] do
              for rank in Rank.GetAllRanks() do 
                  yield { Suit=suit; Rank=rank } ]

    /// 'Card' 개체를 문자열로 변환합니다.
    let showCard c = 
        let rankString = 
            match c.Rank with 
            | Ace -> "Ace"
            | King -> "King"
            | Queen -> "Queen"
            | Jack -> "Jack"
            | Value n -> string n
        let suitString = 
            match c.Suit with 
            | Clubs -> "clubs"
            | Diamonds -> "diamonds"
            | Spades -> "spades"
            | Hearts -> "hearts"
        rankString  + " of " + suitString

    let printAllCards() = 
        for card in fullDeck do 
            printfn "%s" (showCard card)



// ---------------------------------------------------------------
//         옵션 타입
// ---------------------------------------------------------------

module OptionTypes = 
    /// 옵션 값에는 'Some' 또는 'None'으로 태그 처리된 모든 종류의 값을 사용할 수 있습니다.
    /// F# 코드에서 광범위하게 사용되어 다른 언어에서는 null 참조를 사용하는 케이스를
    /// 나타냅니다.

    type Customer = { zipCode : decimal option }

    /// 추상 메서드 'getState' 및 'getShippingZone'에 대한 구현이 있는 경우 
    /// 고객의 우편 번호에 대한 쇼핑 지역을 계산하는 추상 클래스입니다.
    [<AbstractClass>]
    type ShippingCalculator =
        abstract getState : decimal -> string option
        abstract getShippingZone : string -> int

        /// 고객의 우편 번호에 해당하는 쇼핑 지역을 반환합니다.
        /// 고객의 우편 번호가 아직 없거나 우편 번호가 올바르지 않을 수 있습니다.
        member this.customerShippingZone(customer : Customer) =
            customer.zipCode |> Option.bind this.getState |> Option.map this.getShippingZone



// ---------------------------------------------------------------
//         패턴 일치
// ---------------------------------------------------------------

module PatternMatching = 

    /// 사람의 성과 이름에 대한 레코드입니다.
    type Person = {     
        First : string
        Last  : string
    }

    /// 서로 다른 직원 유형이 있는 구분된 공용 구조체 타입을 정의합니다.
    type Employee = 
        | Engineer  of Person
        | Manager   of Person * list<Employee>            // 관리자에게는 부하직원이 있습니다.
        | Executive of Person * list<Employee> * Employee // 또한 간부에게는 비서가 있습니다.

    /// 관리 계층 구조에서 이 직원을 포함하여 이 아래에 있는 모든 직원의 수를 셉니다.
    let rec countReports(emp : Employee) = 
        1 + match emp with
            | Engineer(id) -> 
                0
            | Manager(id, reports) -> 
                reports |> List.sumBy countReports 
            | Executive(id, reports, assistant) ->
                (reports |> List.sumBy countReports) + countReports assistant


    /// 이름이 "Dave"이고 부하직원이 없는 모든 관리자/간부를 찾습니다.
    let rec findDaveWithOpenPosition(emps : Employee list) =
        emps 
        |> List.filter(function 
                       | Manager({First = "Dave"}, []) -> true       // []는 빈 리스트와 일치합니다.
                       | Executive({First = "Dave"}, [], _) -> true
                       | _ -> false)                                 // '_'는 모든 항목과 일치하는 와일드카드 패턴입니다.
                                                                     // "or else"의 경우를 처리합니다.



// ---------------------------------------------------------------
//         측정 단위
// ---------------------------------------------------------------

module UnitsOfMeasure = 

    // 숫자 타입에 대해 F# 산술을 사용할 때 측정 단위를 포함하여 코드에 주석을 추가할 수 있습니다.

    open Microsoft.FSharp.Data.UnitSystems.SI.UnitNames

    [<Measure>]
    type mile =
        /// 마일 대 미터 변환 비율: 미터는 SI.UnitNames에 정의되어 있습니다.
        static member asMeter = 1600.<meter/mile>

    let d  = 50.<mile>          // 임페리얼 단위를 사용하여 표현된 거리입니다.
    let d2 = d * mile.asMeter   // 미터 단위를 사용해서 표현한 동일한 거리입니다.

    printfn "%A = %A" d d2
    // let error = d + d2       // 컴파일 오류: 측정 단위가 일치하지 않습니다.



// ---------------------------------------------------------------
//         병렬 배열 프로그래밍
// ---------------------------------------------------------------

module ParallelArrayProgramming = 
              
    let oneBigArray = [| 0 .. 100000 |]
    
    // CPU를 많이 사용하는 일부 계산을 수행합니다. 
    let rec computeSomeFunction x = 
        if x <= 2 then 1 
        else computeSomeFunction (x - 1) + computeSomeFunction (x - 2)
       
    // 큰 입력 배열에 대해 병렬 맵을 수행합니다.
    let computeResults() = oneBigArray |> Array.Parallel.map (fun x -> computeSomeFunction (x % 20))

    printfn "Parallel computation results: %A" (computeResults())



// ---------------------------------------------------------------
//         이벤트 사용
// ---------------------------------------------------------------

module Events = 

    open System

    // 구독 지점(event.Publish)과 이벤트 트리거(event.Trigger)로 구성된 Event 개체의 인스턴스를 만듭니다.
    let simpleEvent = new Event<int>() 

    // 처리기를 추가합니다.
    simpleEvent.Publish.Add(
        fun x -> printfn "this is handler was added with Publish.Add: %d" x)

    // 이벤트를 트리거합니다.
    simpleEvent.Trigger(5)

    // 표준 .NET 규칙(sender, EventArgs)을 따르는 Event의 인스턴스를 만듭니다.
    let eventForDelegateType = new Event<EventHandler, EventArgs>()    

    // 처리기를 추가합니다.
    eventForDelegateType.Publish.AddHandler(
        EventHandler(fun _ _ -> printfn "this is handler was added with Publish.AddHandler"))

    // 이벤트를 트리거합니다(sender 인수를 설정해야 함).
    eventForDelegateType.Trigger(null, EventArgs.Empty)



// ---------------------------------------------------------------
//         타입 프로바이더를 사용한 데이터베이스 액세스
// ---------------------------------------------------------------

module DatabaseAccess = 
              
    // F#에서 SQL 데이터베이스에 액세스하는 가장 쉬운 방법은 F# 타입 프로바이더를 사용하는 것입니다. 
    // System.Data, System.Data.Linq 및 FSharp.Data.TypeProviders.dll에 대한 참조를 추가합니다.
    // 서버 탐색기를 사용하여 ConnectionString을 만듭니다. 

    (*
    #r "System.Data"
    #r "System.Data.Linq"
    #r "FSharp.Data.TypeProviders"

    open Microsoft.FSharp.Data.TypeProviders
    
    type SqlConnection = SqlDataConnection<ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=tempdb;Integrated Security=True">
    let db = SqlConnection.GetDataContext()

    let table = 
        query { for r in db.Table do
                select r }
    *)


    // SqlDataConnection 대신 SqlEntityConnection을 사용하여 Entity Framework로 데이터베이스에 액세스할 수도 있습니다.

    ()



// ---------------------------------------------------------------
//         타입 프로바이더를 사용한 OData 액세스
// ---------------------------------------------------------------

module OData = 

    (*
    open System.Data.Services.Client
    open Microsoft.FSharp.Data.TypeProviders

    // Azure Marketplace의 인구 통계 및 수입 OData 서비스를 사용합니다. 
    // 자세한 내용은 http://go.microsoft.com/fwlink/?LinkId=239712를 참조하십시오.
    type Demographics = Microsoft.FSharp.Data.TypeProviders.ODataService<ServiceUri = "https://api.datamarket.azure.com/Esri/KeyUSDemographicsTrial/">
    let ctx = Demographics.GetDataContext()

    // Azure Marketplace 계정에 등록하려면 https://datamarket.azure.com/account/info를 방문하십시오.
    ctx.Credentials <- System.Net.NetworkCredential ("<your liveID>", "<your Azure Marketplace Key>")

    let cities = query {
        for c in ctx.demog1 do
        where (c.StateName = "Washington")
        } 

    for c in cities do
        printfn "%A - %A" c.GeographyId c.PerCapitaIncome2010.Value
    *)

    ()



#if COMPILED
module BoilerPlateForForm = 
    [<System.STAThread>]
    do ()
    do System.Windows.Forms.Application.Run()
#endif
