다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 Boo 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 소스 코드에 작성된 함수 convertAtoI(string, radix)와 itoa(number, radix)의 사용이다.

         val as long = convertAtoI(s, srcRdx)
         ret = itoa(val, destRdx)

지원되는 진법은 2진법에서 36진법까지이다.

 또 스트링의 첫글자의 아스키(ascii) 코드값을 구해주는 함수 toAscii(스트링을) 자체 구현하여 사용하였다. 이 함수는 convertAtoI(스트링, radix)에서 (Python의 함수 ord(스트링) 대신) 사용되고 있다.


  1. #  Filename: convertRadix.boo
  2. #            Convert radix in a interactive mode.
  3. #
  4. #  Execute: booi convertRadix.boo
  5. #
  6. #      Date:  2009/04/03
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import System
  9. def println():
  10.     print
  11. def println(s):
  12.     print(s)
  13. def printUsage():
  14.     println("Usage: booi convertRadix.boo")
  15.     println("Convert radix in a interactive mode, where the maximum radix is 36.")
  16. def printAbout():
  17.     println("    About: Convert radix in a interactive mode.")
  18. def printMainMenu():
  19.     println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it")
  20. def printMainPrompt():
  21.     Console.Write("  Prompt> ")
  22. def printSubMenu(srcRadix, destRadix):
  23.     println("    Convert Radix_" + srcRadix + " to Radix_" + destRadix)
  24.     println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit")
  25. def printSubPrompt(): 
  26.     Console.Write("    Input Value>> ")
  27. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  28. def itoa(num as long, radix as int):
  29.    isNegative = false
  30.    if num < 0:
  31.       isNegative = true
  32.       num = -num
  33.    arr as List = []
  34.    q as int = num
  35.    r as int = 0
  36.    while q >= radix:
  37.       r = q % radix
  38.       q = q / radix
  39.       arr.Add(BASE36[r])
  40.    arr.Add(BASE36[q])
  41.    if isNegative:
  42.       arr.Add("-")
  43.    s as string = ""
  44.    n = len(arr)
  45.    for i as int in range(n):
  46.        s += arr[n - 1 - i]
  47.    return s
  48. def toAscii(s as String) as int:
  49.     objAscii as System.Text.ASCIIEncoding = System.Text.ASCIIEncoding()
  50.     val as System.Byte = objAscii.GetBytes(s)[0]
  51.     return Convert.ToInt32(val)
  52. def convertAtoI(srcStr as string, radix as int) as long:
  53.     isNegative = false
  54.     ret as long = 0L
  55.     m = len(srcStr)
  56.     val = 0
  57.     c = srcStr[0:1]
  58.     if toAscii(c) == toAscii('-'):
  59.         isNegative = true
  60.     elif toAscii(c) >= toAscii('0') and toAscii(c) <= toAscii('9'):
  61.         ret = toAscii(c) - toAscii('0')
  62.     elif toAscii(c) >= toAscii('A') and toAscii(c) <= toAscii('Z'):
  63.         ret = (toAscii(c) - toAscii('A')) + 10
  64.     elif toAscii(c) >= toAscii('a') and toAscii(c) <= toAscii('z'):
  65.         ret = (toAscii(c) - toAscii('a')) + 10
  66.     if ret >= radix:
  67.         raise Exception("        invalid character!")
  68.         return ret
  69.     for i in range(1, m):
  70.         c = srcStr[i:i+1]
  71.         ret *= radix
  72.         if toAscii(c) >= char('0') and toAscii(c) <= char('9'):
  73.             val = toAscii(c) - toAscii('0')
  74.         elif toAscii(c) >= char('A') and toAscii(c) <= char('Z'):
  75.             val = (toAscii(c) - toAscii('A')) + 10
  76.         elif toAscii(c) >= char('a') and toAscii(c) <= char('z'):
  77.             val = (toAscii(c) - toAscii('a')) + 10
  78.         if val >= radix:
  79.             raise Exception("        invalid character!")
  80.             return ret
  81.         ret += val
  82.     return ret
  83. def convertRadix(s, srcRdx as int, destRdx as int) as string:
  84.     ret as string = ""
  85.     try:
  86.         val as long = convertAtoI(s, srcRdx)
  87.         ret = itoa(val, destRdx)
  88.         return ret.ToUpper()
  89.     except errMsg:
  90.         print(errMsg + "\n    Error: Cannot convert radix " + srcRdx)
  91.         ret = "????"
  92.     ensure:
  93.         pass
  94.     return ret.ToUpper()
  95. def doConvert(srcRadix as int, destRadix as int):
  96.     line = ""
  97.     cmd = ""
  98.     srcStr = ""
  99.     destStr = ""
  100.     println("")
  101.     printSubMenu(srcRadix, destRadix)
  102.     try:
  103.         while true:
  104.             printSubPrompt()
  105.             cmd = gets()
  106.             if "main()" == cmd:
  107.                 return
  108.             elif "exit()" == cmd or "quit()" == cmd:
  109.                 Environment.Exit(0)
  110.             try:
  111.                 srcStr = cmd
  112.                 destStr = convertRadix(srcStr, srcRadix, destRadix)
  113.                 println("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix)
  114.                 println("")
  115.             except ValueError:
  116.                  pass
  117.     except RuntimeError:
  118.         print "Number Format Error"
  119. def doStart():
  120.     line = ""
  121.     cmd = ""
  122.     srcRadix as int = 10
  123.     destRadix as int = 10
  124.     srcStr = ""
  125.     destStr = ""
  126.     onlyOnce = true
  127.     try:
  128.         while true:
  129.             println()
  130.             if onlyOnce:
  131.                 println("  The supported maximum radix is 36.")
  132.                 onlyOnce = false
  133.             printMainMenu()
  134.             printMainPrompt()
  135.             cmd = gets()
  136.             if "qQxX".IndexOf(cmd) >= 0 and len(cmd) == 1:
  137.                 Environment.Exit(0)
  138.             elif "aA".IndexOf(cmd) >= 0 and len(cmd) == 1:
  139.                 printAbout()
  140.             elif "sS".IndexOf(cmd) >= 0 and len(cmd) == 1:
  141.                 line = prompt("  Input the source and target radices (say, 16 2): ")
  142.                 st = @/\s/.Split(line)
  143.                 while len(st) < 2:
  144.                     line = prompt("  Input the source and target radices (say, 16 2): ")
  145.                     st = @/\s/.Split(line)
  146.                 srcRadix = Convert.ToInt32(st[0])
  147.                 destRadix = Convert.ToInt32(st[1])
  148.                 doConvert(srcRadix, destRadix)
  149.     except RuntimeError:
  150.         print "Number Format Error"
  151. # Begin here
  152. if len(argv) > 0 and "-h" == argv[0]:
  153.     printUsage()
  154.     Environment.Exit(1)
  155. doStart()



실행> booi convertRadix.boo

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 8

    Convert Radix_10 to Radix_8
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 200
        ( 200 )_10   --->   ( 310 )_8

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> S
  Input the source and target radices (say, 16 2): 8 10

    Convert Radix_8 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 2666
        ( 2666 )_8   --->   ( 1462 )_10

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> x




크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Boo 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio


  1. #  Filename: testGoldenRatio.boo
  2. #    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  3. #
  4. #   Execute: booi testGoldenRatio.boo
  5. #
  6. #      Date:  2009/04/01
  7. #    Author: PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import System
  9. def printUsing():
  10.     print("Using: booi testGoldenRatio.boo [-h|-help]")
  11.     print("This calculates the value of the golden ratio.")
  12. # 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  13. def findQuadraticRoot(a as double, b as double, c as double) as List:
  14.     if a == 0.0:
  15.         raise Exception("Since the highest coefficient is zero, the given equation is not a quadratic equation.")
  16.     elif b*b - 4*a*c < 0.0:
  17.         raise Exception("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.")
  18.     x1 = (-b + Math.Sqrt(b*b - 4*a*c)) / (2.0 * a)
  19.     x2 = (-b - Math.Sqrt(b*b - 4*a*c)) / (2.0 * a)
  20.     return [x1, x2]
  21. # 실행 시작 지점
  22. if len(argv) > 0 and (argv[0] == "-h" or argv[0] == "-help"):
  23.     printUsing()
  24.     Environment.Exit(1)
  25. values = findQuadraticRoot(1.0, -1.0, -1.0)
  26. x1 as double = values[0]
  27. x2 as double = values[1]
  28. if x1 >= x2:
  29.     print("The bigger root is " + x1 + ", ")
  30.     print("and the less root is " + x2 + ".")
  31. else:
  32.     print("The bigger root is " + x2 + ", ")
  33.     print("and the less root is " + x1 + ".")



실행> booi testGoldenRatio.boo
The bigger root is 1.61803398875,
and the less root is -0.61803398875.



크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 윈도우 .NET용 애플리케이션의 Boo 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)

아래의 Boo 언어 소스코드는 이전에 등록된 두 가지 소스파일 testCTime.py와 testCTime.cs를 보면 이해가 빠를 것이다.

한글 출력을 정상적으로 볼려면 소스파일을 UTF-8 인코딩으로 저장해야 한다.



  1. #  Filename: testCTime.boo
  2. #  Execute: booi testCTime.boo
  3. import System
  4. # Boo case
  5. weekNames as List = [ "월", "화", "수", "목", "금", "토", "일" ]  
  6. now as DateTime = DateTime.Now
  7. startOfEpoch as DateTime = DateTime(1970, 1, 1)
  8. // 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  9. Console.WriteLine("UTC: " + Convert.ToInt64((DateTime.UtcNow - startOfEpoch).TotalMilliseconds / 1000L))
  10. // 현재 시각 표시: 20xx년 xx월 xx일 (x요일) xx시 xx분 xx초
  11. Console.Write(now.Year + "년 ")
  12. Console.Write(now.Month + "월 ")   // Not 1 + now.Month !!
  13. Console.Write(now.Day + "일 ")
  14. Console.Write("(" + weekNames[Convert.ToInt32(now.DayOfWeek)] + "요일) ")
  15. Console.Write(now.Hour + "시 ")
  16. Console.Write(now.Minute + "분 ")
  17. Console.WriteLine(now.Second + "초")
  18. // 1월 1일은 1, 1월 2일은 2
  19. Console.Write("올해 몇 번째 날: " + now.DayOfYear + ", ")
  20. // True 이면 서머타임 있음
  21. Console.Write("서머타임 적용 여부: ")
  22. if not now.IsDaylightSavingTime():
  23.     Console.Write("안함")
  24. else:
  25.     Console.Write("함")
  26. Console.WriteLine()



실행> booi testCTime.boo
UTC: 1238563106
2009년 4월 1일 (목요일) 14시 18분 25초
올해 몇 번째 날: 91, 서머타임 적용 여부: 안함

실행> booi testCTime.boo
UTC: 1238563109
2009년 4월 1일 (목요일) 14시 18분 29초
올해 몇 번째 날: 91, 서머타임 적용 여부: 안함



크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,

다음은 초등학교에서 배우는 나눗셈 계산표를 만들어주는 Boo 소스 코드이다.
나눗셈 계산표를 완성하고 나서 약수, 배수 관계를 알려준다.

한글 출력을 정상적으로 볼려면 소스파일을 UTF-8 인코딩으로 저장해야 한다.


  1. #  Filename: makeDivisionTable.boo
  2. #
  3. #  Purpose:  Make a division table in a handy written form.
  4. #
  5. #  Execute: booi makeDivisionTable.boo 12345 32
  6. #           booi makeDivisionTable.boo 500210 61
  7. #
  8. #     Date:  2009/04/01
  9. #   Author:  PH Kim   [ pkim ((AT)) scripts.pe.kr ]
  10. import System
  11. def printUsage():
  12.     # print("Using: booi makeDivisionTable.boo [numerator] [denominator]")
  13.     # print("Make a division table in a handy written form.")
  14.     print("사용법: booi makeDivisionTable.boo [피제수] [제수]")
  15.     print("손으로 작성한 형태의 나눗셈 표를 만들어준다.")
  16. def simplify(v as double, width as int):
  17.     t = "${v}"
  18.     if t[-2:] == ".0":
  19.         t = t[0:len(t) - 2]
  20.     slen = len(t)
  21.     if slen < width:
  22.         t = " " * (width - slen) + t
  23.     return t
  24. def getSuffix(v as long):
  25.     t = v % 10L
  26.     suffix = "은"
  27.     if "2459".IndexOf("${t}") >= 0:
  28.         suffix = "는"
  29.     return suffix
  30. def makeTable(numer as long, denom as long, quotient as long):
  31.     strNumer = "${numer}"
  32.     strDenom = "${denom}"
  33.     strQuotient = "${quotient}"
  34.     lenN = len(strNumer)
  35.     lenD = len(strDenom)
  36.     lenQ = len(strQuotient)
  37.     offsetLeft = 3 + lenD + 3
  38.     spaces = "                                                                                 "
  39.     uline  = "_" * (lenN + 2)
  40.     sline  = "-" * lenN
  41.     bias = lenN - lenQ
  42.     print(spaces[0:offsetLeft] + spaces[0:bias] + "${quotient}")
  43.     print(spaces[0:offsetLeft - 2] + uline)
  44.     write("   " + strDenom + " ) " + strNumer)
  45.     strTmpR = strNumer[0: bias + 1]
  46.     tmpR as long = Convert.ToInt64(strTmpR)
  47.     tmpSub as long = 0L
  48.     oneDigit = null
  49.     for i in range(0, lenQ):
  50.         if strQuotient[i: i + 1] == "0":
  51.             if i + 1 < lenQ:
  52.                 oneDigit = strNumer[bias + i + 1: bias + i + 2]
  53.                 write(oneDigit)
  54.                 strTmpR = strTmpR + oneDigit
  55.                 tmpR = Convert.ToInt64(strTmpR)
  56.         else:
  57.             print
  58.             tmpSub = Convert.ToInt64(strQuotient[i: i + 1]) * denom
  59.             print(spaces[0: offsetLeft] + simplify(tmpSub, bias + i + 1))
  60.             print(spaces[0: offsetLeft] + sline)
  61.             tmpR = tmpR - tmpSub
  62.             if tmpR == 0L and i + 1 < lenQ:
  63.                 write(spaces[0: offsetLeft] + spaces[0: bias + i + 1])
  64.             else:
  65.                 write(spaces[0: offsetLeft] + simplify(tmpR, bias + i + 1))
  66.             strTmpR = "${tmpR}"
  67.             if i + 1 < lenQ:
  68.                 oneDigit = strNumer[bias + i + 1: bias + i + 2]
  69.             write(oneDigit)
  70.             strTmpR = strTmpR + oneDigit
  71.             tmpR = Convert.ToInt64(strTmpR)
  72.     print
  73.     return tmpR
  74. def write(s):
  75.     Console.Write(s)
  76. if len(argv) < 2:
  77.     printUsage()
  78.     Environment.Exit(1)
  79. a as long
  80. b as long
  81. try:
  82.     a = Convert.ToInt64(argv[0])
  83.     b = Convert.ToInt64(argv[1])
  84. except ValueError:
  85.     print("피제수: ${argv[0]}, 제수: ${argv[1]}")
  86.     print("숫자 입력에 오류가 있습니다.")
  87.     Environment.Exit(1)
  88. if a <= 0L:
  89.     print("피제수: ${a}")
  90.     print("피제수는 양의 정수라야 합니다.")
  91.     Environment.Exit(1)
  92. elif b <= 0L:
  93.     print("제수: ${b}")
  94.     print("제수는 양의 정수라야 합니다.");
  95.     Environment.Exit(1)
  96. q as long = a / b
  97. r as long = a % b
  98. write("나눗셈 ${a} ÷ ${b} 의 결과: ")
  99. write("몫: ${q}, ")
  100. print("나머지: ${r}")
  101. print
  102. k as long = makeTable(a, b, q)
  103. if k == r:
  104.     print("\n나머지: ${k}")
  105. if k == 0L:
  106.     print("${a} = ${b} x ${q}")
  107.     print("${a}${getSuffix(a)} ${b}의 배수(mupltiple)이다.")
  108.     print("${b}${getSuffix(b)} ${a}의 약수(divisor)이다.")
  109. else:
  110.     print("${a} = ${b} x ${q} + ${r}" % (a, b, q, r)) 
  111.     print("${a}${getSuffix(a)} ${b}의 배수(mupltiple)가 아니다.")




실행> booi makeDivisionTable.boo 500210 61

나눗셈 500210 ÷ 61 의 결과: 몫: 8200, 나머지: 10

          8200
      ________
   61 ) 500210
        488
        ------
         122
         122
        ------
            10

나머지: 10
500210 = 61 x 8200 + 10
500210은 61의 배수(mupltiple)가 아니다.




크리에이티브 커먼즈 라이선스
Creative Commons License



Posted by Scripter
,
다항식 p(x) 를 1차 다항식 x - a 로 나눌 때의 몫과 나머지를 구하는 조립제법을
Boo 언어로 구현해 보았다. 조립제법은 일명 Horner의 방법이라고도 불리우는데, 이는
x = a 에서 다항식 p(x)의 값 p(a)을 계산하는 가장 빠른 알고리즘이기도 하다.

         p(x) = (x - a)q(x) + r

여기서 r은 나머지이며 r = p(a) 이다. 또 q(x)는 몫이다.

[참고]
    * 온라인으로 조립제법 표 만들기 손으로 계산하는 조립제법 표 
    * 온라인으로 구하는 다항식의 도함수: 조립제법을 이용한 다항식의 도함수


아래의 소스파일은 Python용 소스파일 testSyntheticDivision.py를 Boo용으로 수정한 것이다.
소스파일을 저장할 때는 UTF-8 인코딩으로 저장해야 한다.

Boo  언어는 그 구문의 바탕을 Python 언어의 것에서 빌렸다.
그러나 Python 언어는 변수의 타입이 런타임시에 결정되는 동적 타입(dynamically typed) 언어이지만, Boo 언어는 변수의 타입이 컴파일시에 결정되는 정적 타입(statically typed) 언어라는 점에서 차이점이 있다.

      (1) 함수를 구현할 때 매개변수의 타입을 지정해야 한다.
      (2) 변수 선언시에 타입을 지정해야 하는 경우가 많다.
      (3) 리스트에서 가져온 데이터의 타입을 다시 지정해야 한다.



  1. #  Filename: testSyntheticDivision.boo
  2. #
  3. #  Purpose:  Find the quotient and remainder when some polynomial is
  4. #            divided by a monic polynomial of the first degree.
  5. #
  6. #  Execute:  booi testSyntheticDivision.boo -2 1 3 3 1
  7. import System
  8. # 사용법 표시
  9. def printUsage():
  10.     print("사용법: booi testSyntheticDivision.boo [수] [피제식의 계수들]")
  11.     print("조립제법(synthetic method)에 의한 다항식 나눗셈 결과를 보여준다.")
  12. # 부동소수점수의 표현이 .0 으로 끝나는 경우 이를 잘라낸다.
  13. # 전체 문자열 표시 너비는 매개변수 width 로 전달받아 처리한다.
  14. def simplify(v as double, width as int):
  15.     t = "${v}"
  16.     tlen = len(t)
  17.     if t[tlen-2:tlen-1] == ".0":
  18.         t = t[0:-2]
  19.     if width > 0:
  20.         if tlen < width:
  21.             t = "              "[0: width - tlen] + t
  22.     return t
  23. # 다항식을 내림차순의 스트링 표현으로 반환
  24. def toPolyString(c as List):
  25.     t = ""
  26.     sc0 = simplify(Convert.ToDouble(c[0]), -1)
  27.     if len(c) > 2:
  28.         if sc0 == "1":
  29.             t += "x^${len(c)-1}"
  30.         elif sc0 == "-1":
  31.             t += "-x^${len(c)-1}"
  32.         else:
  33.             t += sc0 + " x^${len(c)-1}"
  34.     elif len(c) == 2:
  35.         if sc0 == "1":
  36.             t += "x"
  37.         elif sc0 == "-1":
  38.             t += "-x"
  39.         else:
  40.             t += sc0 + " x"
  41.     elif len(c) == 1:
  42.         t += sc0
  43.     for i in range(1, len(c)):
  44.         k = len(c) - 1 - i
  45.         sc = simplify(Convert.ToDouble(c[i]), -1)
  46.         if k > 1:
  47.             if Convert.ToDouble(c[i]) > 0.0:
  48.                 if sc == "1":
  49.                     t += " + " + "x^${k}"
  50.                 else:
  51.                     t += " + " + sc + " x^${k}"
  52.             elif Convert.ToDouble(c[i]) < 0.0:
  53.                 if sc == "-1":
  54.                     t += " - " + "x^${k}"
  55.                 else:
  56.                     t += " - " + simplify(Math.Abs(Convert.ToDouble(c[i])), -1) + " x^${k}"
  57.         elif k == 1:
  58.             if Convert.ToDouble(c[i]) > 0.0:
  59.                 if sc == "1":
  60.                     t += " + " + "x"
  61.                 else:
  62.                     t += " + " + sc + " x"
  63.             elif Convert.ToDouble(c[i]) < 0.0:
  64.                 if sc == "-1":
  65.                     t += " - " + "x"
  66.                 else:
  67.                     t += " - " + simplify(Math.Abs(Convert.ToDouble(c[i])), -1) + " x"
  68.         elif k == 0:
  69.             if Convert.ToDouble(c[i]) > 0.0:
  70.                 t += " + " + sc
  71.             elif Convert.ToDouble(c[i]) < 0.0:
  72.                 t += " - " + simplify(Math.Abs(Convert.ToDouble(c[i])), -1)
  73.     return t
  74. # 다향식 나눗셈 결과를
  75. #     (피제식) = (제식)(몫) + (나마지)
  76. # 형태로 출력
  77. def printDivisionResult(a as double, c as List, b as List):
  78.     strLine = "  " + toPolyString(c)
  79.     print( strLine )
  80.     strLine = "    = ( " + toPolyString( [1.0, -a] ) + " )"
  81.     tmp = [0.0] * (len(b) - 1)
  82.     for i in range(0, len(tmp)):
  83.         tmp[i] = b[i]
  84.     strLine += "( " + toPolyString(tmp) + " )"
  85.     r as double = b[len(b) - 1]
  86.     if r > 0.0:
  87.         strLine += " + " + simplify(r, -1)
  88.     elif r < 0.0:
  89.         strLine += " - " + simplify(Math.Abs(r), -1)
  90.     print( strLine )
  91. # 조립제법 계산표 출력 함수
  92. def printSyntheticTable(a, c as List, s as List, q as List):
  93.     strLine = "       | "
  94.     strLine += simplify(c[0], 6)
  95.     for i in range(1, len(c)):
  96.         strLine += "  " + simplify(c[i], 6)
  97.     print( strLine )
  98.     strLine = simplify(a, 6) + " |"
  99.     strLine += "         "
  100.     strLine += simplify(s[1], 6)
  101.     for i in range(2, len(s)):
  102.         strLine += "  " + simplify(s[i], 6)
  103.     print( strLine )
  104.     strLine = "       |"
  105.     for i in range(0, len(q)):
  106.         strLine += "--------"
  107.     print( strLine )
  108.     strLine = "         "
  109.     strLine += simplify(Convert.ToDouble(q[0]), 6)
  110.     for i in range(1, len(q)):
  111.         strLine += "  " + simplify(Convert.ToDouble(q[i]), 6)
  112.     print( strLine )
  113. def write(s):
  114.     Console.Write(s)
  115. # 실행 시작 지점
  116. if len(argv) < 2:
  117.     printUsage()
  118.     Environment.Exit(1)
  119. ######################################################
  120. # 피제식은 c_0 x^n +  c_1 x^(n -1) + ... + c_n
  121. # 제식은 x -  a 
  122.  as double = Convert.ToDouble(argv[0])
  123. c as List = [0.0]*(len(argv) - 1)
  124. s as List = [0.0]*(len(argv) - 1)
  125. b as List = [0.0]*(len(argv) - 1)
  126. for i in range(0, len(c)):
  127.     c[i] = Convert.ToDouble(argv[i + 1])
  128. ######################################################
  129. # 조립제법의 주요 부분
  130. s[0] = 0.0
  131. b[0] = c[0]
  132. for i in range(1, len(c)):
  133.     s[i] = Convert.ToInt32(b[i-1])*a
  134.     b[i] = Convert.ToInt32(c[i]) + Convert.ToInt32(s[i])
  135. ######################################################
  136. # 몫의 계수와 나머지를 출력한다.
  137. write("몫의 계수는 ")
  138. for i in range(0, len(b) - 2):
  139.     write(simplify(b[i], -1) + ", ")
  140. write(simplify(b[len(b) - 2], -1))
  141. write(" 이고, 나머지는 " + simplify(b[len(b) - 1], -1) + " 이다.")
  142. print
  143. print
  144. ######################################################
  145. # 조립제법 표를 출력한다.
  146. printSyntheticTable(a, c, s, b)
  147. print
  148. ######################################################
  149. # (피제식) = (제식) x (몫) + (나머지)
  150. printDivisionResult(a, c, b)




실행> booi testSyntheticDivision.boo 1 2 3 4 5
몫의 계수는 2, 5, 9 이고, 나머지는 14 이다.

       |      2       3       4       5
     1 |              2       5       9
       |---------------------------------
              2       5       9      14

  2 x^3 + 3 x^2 + 4 x + 5
    = ( x - 1 )( 2 x^2 + 5 x + 9 ) + 14



크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,
다음은 Python용 소스파일 testForFor.py를 Boo용으로 수정한 것이다.
print 문에 쓰일 스트링은 Groovy 언어의 GString 처럼 작성하면 된다.
(Groovy 언어에서는 GString이라고 하지만, Boo 언어에서는 string interpolation이라고 한다.)
(Groovy 언어의 GString에서는 "$표현식"와 "${표현식}"가 둘 다 가능하지만, Boo 언어의 string interpolation에서는 "${표현식}"만 가능하다.)

Boo 언어의 if...else... 조건문 양식은 Python 언어에서와 같이

        if 조건식1:
            블럭1
        elif 조건식2:
            블럭2
        elif 조건식3:
            블럭3
        else:
            블럭4

이다.

같은 것이 반복되는 List 생성 구문

         t as List = [""]*19

은 Groovy, Python, Ruby 언어의 것과 유사하다.

함수 printAllNineteenDan()의 구현부에서

         arr = array(List, 18) 

라고 리스트의 배열로 처리한 것은 Boo 언어에서 arr[번호][번호] 형식의 구문으로 자료를 가져오기 위해서이다.


  1. #  Filename: testForFor.boo
  2. #
  3. #  Execute:  booi testForFor.boo
  4. #
  5. #  Date:  2098. 4. 1
  6. import System
  7. import System.Collections
  8. def getDan(dan as int) as List:
  9.     t as List = [""]*19
  10.     for j in range(0,  19):
  11.         sa = "${dan}"
  12.         if len(sa) < 2:
  13.             sa = " ${dan}"
  14.         sb = "${j + 1}"
  15.         if len(sb) < 2:
  16.             sb = " ${j + 1}"
  17.         sval = "${dan*(j + 1)}"
  18.         if len(sval) < 2:
  19.             sval = "  ${dan*(j + 1)}"
  20.         elif len(sval) < 3:
  21.             sval = " ${dan*(j + 1)}"
  22.         t[j] = sa + " x " + sb + " = " + sval
  23.     return t
  24. # 19단표를 모두 80컬럼 컨솔에 출력한다.
  25. def printAllNineteenDan():
  26.     arr = array(List, 18)   # Boo 소스 코드에서는 리스트의 배열이다.
  27.     for i in range(2, 20):
  28.         arr[i - 2] = getDan(i)
  29.     # Boo 소스 코드에서도 배열 대신 리스트를 사용한다.
  30.     d as List = [ 2, 7, 11, 16 ]      # 각 줄단위 블럭의 첫단
  31.     counter as List = [ 5, 4, 5, 4 ]  # 각 줄단위 블럭에 속한 단의 개수
  32.     lines as List = [""]*19
  33.     for k as int in range(0, len(d)):
  34.         # 8-바이트 길이의 한 줄씩 완성
  35.         for i as int in range(0, 19):
  36.             lines[i] = arr[Convert.ToInt32(d[k])-2][i]
  37.             for j as int in range(1, counter[k]):
  38.                 lines[i] += "   " +  arr[Convert.ToInt32(d[k])-2+j][i]
  39.         # 80 바이트 길이의 한 줄씩 출력
  40.         for i as int in range(0, 19):
  41.             print lines[i]
  42.         print
  43. printAllNineteenDan()



실행> booi testForFor.boo 

2 x  1 =   2    3 x  1 =   3    4 x  1 =   4    5 x  1 =   5    6 x  1 =   6
2 x  2 =   4    3 x  2 =   6    4 x  2 =   8    5 x  2 =  10    6 x  2 =  12
2 x  3 =   6    3 x  3 =   9    4 x  3 =  12    5 x  3 =  15    6 x  3 =  18
2 x  4 =   8    3 x  4 =  12    4 x  4 =  16    5 x  4 =  20    6 x  4 =  24
2 x  5 =  10    3 x  5 =  15    4 x  5 =  20    5 x  5 =  25    6 x  5 =  30
2 x  6 =  12    3 x  6 =  18    4 x  6 =  24    5 x  6 =  30    6 x  6 =  36
2 x  7 =  14    3 x  7 =  21    4 x  7 =  28    5 x  7 =  35    6 x  7 =  42
2 x  8 =  16    3 x  8 =  24    4 x  8 =  32    5 x  8 =  40    6 x  8 =  48
2 x  9 =  18    3 x  9 =  27    4 x  9 =  36    5 x  9 =  45    6 x  9 =  54
2 x 10 =  20    3 x 10 =  30    4 x 10 =  40    5 x 10 =  50    6 x 10 =  60
2 x 11 =  22    3 x 11 =  33    4 x 11 =  44    5 x 11 =  55    6 x 11 =  66
2 x 12 =  24    3 x 12 =  36    4 x 12 =  48    5 x 12 =  60    6 x 12 =  72
2 x 13 =  26    3 x 13 =  39    4 x 13 =  52    5 x 13 =  65    6 x 13 =  78
2 x 14 =  28    3 x 14 =  42    4 x 14 =  56    5 x 14 =  70    6 x 14 =  84
2 x 15 =  30    3 x 15 =  45    4 x 15 =  60    5 x 15 =  75    6 x 15 =  90
2 x 16 =  32    3 x 16 =  48    4 x 16 =  64    5 x 16 =  80    6 x 16 =  96
2 x 17 =  34    3 x 17 =  51    4 x 17 =  68    5 x 17 =  85    6 x 17 = 102
2 x 18 =  36    3 x 18 =  54    4 x 18 =  72    5 x 18 =  90    6 x 18 = 108
2 x 19 =  38    3 x 19 =  57    4 x 19 =  76    5 x 19 =  95    6 x 19 = 114

7 x  1 =   7    8 x  1 =   8    9 x  1 =   9   10 x  1 =  10
7 x  2 =  14    8 x  2 =  16    9 x  2 =  18   10 x  2 =  20
7 x  3 =  21    8 x  3 =  24    9 x  3 =  27   10 x  3 =  30
7 x  4 =  28    8 x  4 =  32    9 x  4 =  36   10 x  4 =  40
7 x  5 =  35    8 x  5 =  40    9 x  5 =  45   10 x  5 =  50
7 x  6 =  42    8 x  6 =  48    9 x  6 =  54   10 x  6 =  60
7 x  7 =  49    8 x  7 =  56    9 x  7 =  63   10 x  7 =  70
7 x  8 =  56    8 x  8 =  64    9 x  8 =  72   10 x  8 =  80
7 x  9 =  63    8 x  9 =  72    9 x  9 =  81   10 x  9 =  90
7 x 10 =  70    8 x 10 =  80    9 x 10 =  90   10 x 10 = 100
7 x 11 =  77    8 x 11 =  88    9 x 11 =  99   10 x 11 = 110
7 x 12 =  84    8 x 12 =  96    9 x 12 = 108   10 x 12 = 120
7 x 13 =  91    8 x 13 = 104    9 x 13 = 117   10 x 13 = 130
7 x 14 =  98    8 x 14 = 112    9 x 14 = 126   10 x 14 = 140
7 x 15 = 105    8 x 15 = 120    9 x 15 = 135   10 x 15 = 150
7 x 16 = 112    8 x 16 = 128    9 x 16 = 144   10 x 16 = 160
7 x 17 = 119    8 x 17 = 136    9 x 17 = 153   10 x 17 = 170
7 x 18 = 126    8 x 18 = 144    9 x 18 = 162   10 x 18 = 180
7 x 19 = 133    8 x 19 = 152    9 x 19 = 171   10 x 19 = 190

11 x  1 =  11   12 x  1 =  12   13 x  1 =  13   14 x  1 =  14   15 x  1 =  15
11 x  2 =  22   12 x  2 =  24   13 x  2 =  26   14 x  2 =  28   15 x  2 =  30
11 x  3 =  33   12 x  3 =  36   13 x  3 =  39   14 x  3 =  42   15 x  3 =  45
11 x  4 =  44   12 x  4 =  48   13 x  4 =  52   14 x  4 =  56   15 x  4 =  60
11 x  5 =  55   12 x  5 =  60   13 x  5 =  65   14 x  5 =  70   15 x  5 =  75
11 x  6 =  66   12 x  6 =  72   13 x  6 =  78   14 x  6 =  84   15 x  6 =  90
11 x  7 =  77   12 x  7 =  84   13 x  7 =  91   14 x  7 =  98   15 x  7 = 105
11 x  8 =  88   12 x  8 =  96   13 x  8 = 104   14 x  8 = 112   15 x  8 = 120
11 x  9 =  99   12 x  9 = 108   13 x  9 = 117   14 x  9 = 126   15 x  9 = 135
11 x 10 = 110   12 x 10 = 120   13 x 10 = 130   14 x 10 = 140   15 x 10 = 150
11 x 11 = 121   12 x 11 = 132   13 x 11 = 143   14 x 11 = 154   15 x 11 = 165
11 x 12 = 132   12 x 12 = 144   13 x 12 = 156   14 x 12 = 168   15 x 12 = 180
11 x 13 = 143   12 x 13 = 156   13 x 13 = 169   14 x 13 = 182   15 x 13 = 195
11 x 14 = 154   12 x 14 = 168   13 x 14 = 182   14 x 14 = 196   15 x 14 = 210
11 x 15 = 165   12 x 15 = 180   13 x 15 = 195   14 x 15 = 210   15 x 15 = 225
11 x 16 = 176   12 x 16 = 192   13 x 16 = 208   14 x 16 = 224   15 x 16 = 240
11 x 17 = 187   12 x 17 = 204   13 x 17 = 221   14 x 17 = 238   15 x 17 = 255
11 x 18 = 198   12 x 18 = 216   13 x 18 = 234   14 x 18 = 252   15 x 18 = 270
11 x 19 = 209   12 x 19 = 228   13 x 19 = 247   14 x 19 = 266   15 x 19 = 285

16 x  1 =  16   17 x  1 =  17   18 x  1 =  18   19 x  1 =  19
16 x  2 =  32   17 x  2 =  34   18 x  2 =  36   19 x  2 =  38
16 x  3 =  48   17 x  3 =  51   18 x  3 =  54   19 x  3 =  57
16 x  4 =  64   17 x  4 =  68   18 x  4 =  72   19 x  4 =  76
16 x  5 =  80   17 x  5 =  85   18 x  5 =  90   19 x  5 =  95
16 x  6 =  96   17 x  6 = 102   18 x  6 = 108   19 x  6 = 114
16 x  7 = 112   17 x  7 = 119   18 x  7 = 126   19 x  7 = 133
16 x  8 = 128   17 x  8 = 136   18 x  8 = 144   19 x  8 = 152
16 x  9 = 144   17 x  9 = 153   18 x  9 = 162   19 x  9 = 171
16 x 10 = 160   17 x 10 = 170   18 x 10 = 180   19 x 10 = 190
16 x 11 = 176   17 x 11 = 187   18 x 11 = 198   19 x 11 = 209
16 x 12 = 192   17 x 12 = 204   18 x 12 = 216   19 x 12 = 228
16 x 13 = 208   17 x 13 = 221   18 x 13 = 234   19 x 13 = 247
16 x 14 = 224   17 x 14 = 238   18 x 14 = 252   19 x 14 = 266
16 x 15 = 240   17 x 15 = 255   18 x 15 = 270   19 x 15 = 285
16 x 16 = 256   17 x 16 = 272   18 x 16 = 288   19 x 16 = 304
16 x 17 = 272   17 x 17 = 289   18 x 17 = 306   19 x 17 = 323
16 x 18 = 288   17 x 18 = 306   18 x 18 = 324   19 x 18 = 342
16 x 19 = 304   17 x 19 = 323   18 x 19 = 342   19 x 19 = 361


 
크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,

Boo 언어의 while... 반복문 구문은 Python 언어의 그것과 동일하다.

        while 조건식:
                블럭

스트링을 긴정수(즉 64비트 정수) 타입으로 변환하는 변수에 저장하는 Boo 언어의 구문은

        변수명 as long = Convert.ToInt64(스트링)

이다.



소스 파일명: testWhile.boo

  1. # Filename: testWhile.boo
  2. #
  3. # Purpose:  Example using the while loop syntax
  4. #                while ....
  5. #
  6. # Execute: booi testWhile.boo -200 300
  7. #
  8. import System
  9. # 사용법 표시
  10. def printUsage():
  11.     print "Using: booi testWhile.boo [integer1] [integer2]"
  12.     print "This finds the greatest common divisor of the given two integers."
  13. if argv.Length != 2:
  14.     printUsage()
  15.     Environment.Exit(1)
  16. # --------------------------------------
  17. # 명령행 인자의 두 스트링을 가져와서
  18. # 정수 타입으로 변환하여
  19. # 변수 val1과 val2에 저장한다.
  20. val1 as long = Convert.ToInt64(argv[0])
  21. val2 as long = Convert.ToInt64(argv[1])
  22. # a는 |val1|, |val2| 중 큰 값
  23. a as long = Math.Abs(val1)
  24. b as long = Math.Abs(val2)
  25. if a < b:
  26.     a = Math.Abs(val2)
  27.     b = Math.Abs(val1)
  28. if b == 0:
  29.     print "GCD(${val1}, ${val2}) = ${a}"
  30.     Environment.Exit(1)
  31. # --------------------------------------
  32. # Euclidean 알고리즘의 시작
  33. #
  34. # a를 b로 나누어 몫은 q에, 나머지는 r에 저장
  35. q = a / b
  36. r = a % b
  37. # --------------------------------------
  38. # Euclidean 알고리즘의 반복 (나머지 r이 0이 될 때 까지)
  39. while r != 0:
  40.     a = b
  41.     b = r
  42.     q = a / b
  43.     r = a % b
  44. # 나머지가 0이면 그 때 나눈 수(제수) b가 최대공약수(GCD)이다.
  45. gcd = b
  46. # 최대공약수(GCD)를 출력한다.
  47. print "GCD(${val1}, ${val2}) = ${gcd}"

 

실행:

Command> booi testWhile.boo
Using: booi testWhile.boo [integer1] [integer2]
This finds the greatest common divisor of the given two integers.

Command> booi testWhile.boo -200 300
GCD(-200, 300) = 100

Command> booi testWhile.boo -200 0
GCD(-200, 0) = 200

Command> booi testWhile.boo 125 100
GCD(125, 100) = 25

Command> booi testWhile.boo 23 25
GCD(23, 25) = 1


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,

Boo  언어의 if...else... 구문은 Python 언어의 그것과 동일하다.

        if 조건식:
                ......
        elif 조건식:
                ......
        elif 조건식:
                .......
        else:
                ......


Boo  언어의 주석문은 Python 언어의 것을 써도 되고, C 언어의 것을 써도 된다.

     한 줄 주석문
            // 주석...
       또는
            # 주석...

     여러 줄 주석문
            /*
                    주석... 
                    */
       또는
            """
                    주석...       
                    """


소스 파일명: testIf.boo

  1. """
  2.    Filename: testIf.boo
  3.    Purpose:  Example using the conditional control structure syntax
  4.                  if .... else ...
  5.    Execute: booi testIf.boo [number]
  6. """
  7. import System    // Convert.ToDouble()과 Environment.Exit()을
  8.                  // 사용하기 위한 Boo 언어의 수입(import) 구문
  9. # 사용법을 보여주는 함수
  10. def printUsing():
  11.    print("Using: booi testIf.boo [number]")
  12.    print("This determines whether the number is positive or not.")
  13. # 명령행 인자의 개수가 1이 아니면 사용법을 보여준다.
  14. if argv.Length != 1:
  15.     printUsing()
  16.     Environment.Exit(1)
  17. # 명령행 인자의 스트링을 가져와서
  18. # 배정밀도 부동소수점수로 변환하여
  19. # 변수 val에 저장한다.
  20. val as double = Convert.ToDouble(argv[0])
  21. # 변수 val에 저장된 값이 양수인지 음수인지 0인지를
  22. # 판단하는 if...else... 조건문
  23. if val > 0.0:
  24.     print("${val} is a positive number.")
  25. elif val < 0.0:
  26.     print("${val} is a negative number.")
  27. else:
  28.     print("${val} is zero.")




실행> booi testIf.boo
Using: booi testIf.boo [number]
This determines whether the number is positive or not.

실행> booi testIf.boo 6.25
6.25 is a positive number.

실행> booi testIf.boo -6.25
-6.25 is a negative number.

실행> booi testIf.boo 0
0 is zero.


※ 컴파일 명령 booc로 위의 소스 코드로 부터 .NET용 실행파일을 만들 수 있다.
booc testIf.boo

컴파일> booc -out:TestIf.exe testIf.boo
실행> TestIf 1.02
1.02 is a positive number.

실행> TestIf -1.02
-1.02 is a negative number.

실행> TestIf 0
0 is zero.



 

크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,

윈도우 계열에서 Boo 언어는 .NET 환경에서 동작한다.
Boo 언어의 구문 몸체는 Python 언어의 것을 빌려 왔지만,
IronPython 처럼 그 실행 환경을 .NET으로 삼고 있다.
(Boo 언어의 소스코드에서도 Python 언어 처럼 들여쓰기가 중요하다.)

Python 언어에서 명령행 인자는 sys.argv 라는 변수로 처리하지만,
Boo 언어에서 명령행 인자는 argv 라는 변수로 처리한다.
명령행 인자의 갯수는 argv.Length의 값으로 알 수 있다.
(Python 언어에서 처럼 len() 함수를 써서 len(argv)로 해도 된다.)

또 스트링을 부동소수점수로 변환할 때는 System.Convert.ToDouble(스트링)을 사용한다.
import System 구문을 사용하였으면  Convert.ToDouble(스트링)으로 줄여서 쓸 수 있다.
(Python 언어에서는 float(스트링), Groovy 언어에서는 스트링.toDouble())

수입(import)구문 비교

        C# 언어에서는 
                using System;

        Boo 언어에서는 
                import System




소스파일명: testArguments.boo

  1. import System
  2. sum as double = 0.0
  3. // 명령행 인자(command-line argument) 개수 출력
  4. print("Count of arguments: ${argv.Length}")
  5. for i in range(0, argv.Length):
  6.     // 스트링을 배정밀도 부동소수점수로 변환하여 누적
  7.     sum += Convert.ToDouble(argv[i])
  8.     // 출력 값이 ".0"으로 끝나는 경우 꼬리 제거하기
  9.     strSum = "" + sum;
  10.     if strSum.EndsWith(".0"):
  11.         strSum = strSum[:-1]
  12. // 누적된 값을 출력한다.
  13. print("The sum of arguments is ${strSum}")



실행> booi testArguments.boo 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


실행> booi testArguments.boo 1 2 3 4.1
Count of arguments: 4
The sum of arguments is 10.1


※ 위의 소스 코드는 booc 명령으로 .NET 용 실행파일을 만들 수도 있다.

컴파일> booc testArguments.boo
   실행> testArguments 1 2 3 4
Count of arguments: 4
The sum of arguments is 10


 

크리에이티브 커먼즈 라이선스
Creative Commons License


 

Posted by Scripter
,

Boo 언어의 구문은 Python 언어의 그것과 매우 닮았다.

       def functionName(parameter1  as 타입1, ... , parameterN  as 타입N):
             block

이다.

또 Boo 언어의 반복문 양식은 Python  언어 처럼

       for varName in Range:
             block

이다.

또 Boo 언어의 print 문은 Python  언어의 것과 Groovy 언의의 것을 섞어 놓은 듯하다.
즉, Python 언어의 print 문 처럼 새줄 문자(\n)를 출력하며, Groovy 언어의 print 문처럼 GString을 스트링으로 변환하여 출력한다.


소스 파일명: forTest.boo
------------------------------[소스 시작]
def printDan(dan as int):
  for i in range(1, 10):
    print "${dan} x ${i} = ${dan*i}"

printDan(2)
------------------------------[소스 끝]

실행> booi forTest.boo
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18



컴파일 후 실행하기

컴파일> booc forTest.boo
실행> forTest
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18




크리에이티브 커먼즈 라이선스
Creative Commons License


Posted by Scripter
,