Boo 언어 소스:

#  Filename: testHexView_02.boo
#
#   Execute: booi testHexView_02.boo [filename]
#
#    Or
#
#   Compile: booc testHexView_02.boo
#   Execute: testHexView_02 [filename]
#
# Date: 2013. 8. 16.

import System
import System.IO

def printUsage():
    print "Usage: booi testHexView_02 [filename]"

def isDirectory(path as string) as bool:
    fa = System.IO.File.GetAttributes(path)
    isDir = false
    if (fa & FileAttributes.Directory) != 0:
        isDir = true
    return isDir

def ascii(s as string) as int:
    arr = array(s)
    n = cast(int, arr[0])
    return n

def toChar(n as int) as char:
    a = cast(char, n)
    return a

def toHex(b as int) as string:
    s = ""
    x1 = (b & 0xF0) >> 4
    x2 = b & 0x0F
    if x1 < 10:
        s += toChar(ascii('0') + x1)
    else:
        s += toChar((x1 - 10) + ascii('A'))
    if x2 < 10:
        s += toChar(ascii('0') + x2)
    else:
        s += toChar((x2 - 10) + ascii('A'))
    return s

def toHex8(n as int) as string:
    s = ""
    x1 = (n & 0xF0000000) >> 28
    x2 = (n & 0xF000000) >> 24
    x3 = (n & 0xF00000) >> 20
    x4 = (n & 0xF0000) >> 16
    x5 = (n & 0xF000) >> 12
    x6 = (n & 0xF00) >> 8
    x7 = (n & 0xF0) >> 4
    x8 = n & 0x0F
    if x1 < 10:
        s += toChar(ascii('0') + x1)
    else:
        s += toChar((x1 - 10) + ascii('A'))
    if x2 < 10:
        s += toChar(ascii('0') + x2)
    else:
        s += toChar((x2 - 10) + ascii('A'))
    if x3 < 10:
        s += toChar(ascii('0') + x3)
    else:
        s += toChar((x3 - 10) + ascii('A'))
    if x4 < 10:
        s += toChar(ascii('0') + x4)
    else:
        s += toChar((x4 - 10) + ascii('A'))
    s += ' '
    if x5 < 10:
        s += toChar(ascii('0') + x5)
    else:
        s += toChar((x5 - 10) + ascii('A'))
    if x6 < 10:
        s += toChar(ascii('0') + x6)
    else:
        s += toChar((x6 - 10) + ascii('A'))
    if x7 < 10:
        s += toChar(ascii('0') + x7)
    else:
        s += toChar((x7 - 10) + ascii('A'))
    if x8 < 10:
        s += toChar(ascii('0') + x6)
    else:
        s += toChar((x8 - 10) + ascii('A'))
    return s

if argv.Length < 1:
    printUsage()
    Environment.Exit(1)

filename = argv[0]
if isDirectory(filename):
    Console.WriteLine("The file \"" + filename + "\" is a directory.")
    Environment.Exit(1)

if not File.Exists(filename):
    print "The file \"" + filename + "\" does not exist."
    return

fileSize = FileInfo(filename).Length;
print "The size of the file \"" + filename + "\" is " + fileSize + "."
print

br = BinaryReader(File.Open(filename, FileMode.Open))
dum = ""
n = 0L
while n < fileSize:
    if n % 16 == 0L:
        Console.Write(toHex8(n) + ": ")
    data = br.ReadByte()
    if n % 16 != 8L:
        Console.Write(" ")
    else:
        Console.Write("-")
    Console.Write(toHex(data))

    if (data & 0xFF) >= 0x20 and (data & 0xFF) <= 0x7E:
        dum += toChar(data & 0xFF)
    else:
        dum += "."

    if n > 0 and n % 16 == 15L:
        Console.Write("  |")
        Console.Write(dum)
        Console.Write("|")
        Console.WriteLine()
        dum = ""

    n += 1

if n > 0 and n % 16 > 0:
    for i in range(16 - (n % 16)):
        Console.Write("   ")
    Console.Write("  |")
    Console.Write(dum)
    for i in range(16 - (n % 16)):
        Console.Write(" ")
    Console.Write("|")
    Console.WriteLine()
    dum = ""

Console.WriteLine()
Console.WriteLine("Read " + n + " bytes.")

 

실행 예 1> booi testHexView_02.boo temp_1.bin
The size of the file "temp_1.bin" is 12.

0000 0000:  48 65 6C 6C 6F 20 74 68-65 72 65 0A              |Hello there.    |

Read 12 bytes.

실행 예 2> booi testHexView_02.boo myFile.ser
The size of the file "myFile.ser" is 130.

0000 0000:  AC ED 00 05 73 72 00 06-50 65 72 73 6F 6E 07 31  |....sr..Person.1|
0000 0010:  46 DB A5 1D 44 AB 02 00-03 49 00 03 61 67 65 4C  |F...D....I..ageL|
0000 0020:  00 09 66 69 72 73 74 4E-61 6D 65 74 00 12 4C 6A  |..firstNamet..Lj|
0000 0030:  61 76 61 2F 6C 61 6E 67-2F 53 74 72 69 6E 67 3B  |ava/lang/String;|
0000 0040:  4C 00 08 6C 61 73 74 4E-61 6D 65 71 00 7E 00 01  |L..lastNameq.~..|
0000 0050:  78 70 00 00 00 13 74 00-05 4A 61 6D 65 73 74 00  |xp....t..Jamest.|
0000 0060:  04 52 79 61 6E 73 71 00-7E 00 00 00 00 00 1E 74  |.Ryansq.~......t|
0000 0070:  00 07 4F 62 69 2D 77 61-6E 74 00 06 4B 65 6E 6F  |..Obi-want..Keno|
0000 0080:  62 69                                            |bi              |

Read 130 bytes.

 

 

Posted by Scripter
,

역삼각함수란 삼각함수의 역함수를 의미하고,

역쌍곡선함수란 쌍곡선함수의 역함수를 의미한다.

수학에서 sin 함수의 역함수는 arcsin 으로 표기되는데,

Boo 언어에서는 닷넷에서 사용하는  Math.Asin() 함수를 쓰면 된다.

이를 사용하기 위해서는 import 구문

import System

이 필요하다.

 

Boo 언어는 Pytyhon 언어와 비슷하며, 닷넷 용이라는 점에서는 IronPython 과 더더욱 비슷하다.

다음 소스는 Boo 인타프리터 booi 로 실행해도 되고, Boo 컴파일러 booc 로 컴파일하여 생성된 실행 파일을 실행해도 된다. booc 로 컴파일이 성공적으로 끝나면 *.exe 파일과 *.pdb 파일이 생성된다.

#  Filename: testArcSine.boo
#
#   Execute: booi testArcSine.boo
#
#    Or
#
#   Compile: booc testArcSine.boo
#   Execute: testArcSine.boo
#
# Date: 2013. 1. 6.
# Copyright (c) pkim _AT_ scripts.pe.kr

import System

def asinh(x as double) as double:
    y = Math.Log(x + Math.Sqrt(x*x + 1))
    return y

def acosh(x as double) as double:
    y = Math.Log(x + Math.Sqrt(x*x - 1))
    return y


# 실행 시작 지점
x = -0.9
y = Math.Asin(x)
print string.Format("y = asin({0}) = {1:F9}", x,  y)
print string.Format("sin(y) = sin({0:F9}) = {1}", y, Math.Sin(y))
print

x = 1.1
u = acosh(x)
print string.Format("u = acosh({0}) = {1:F10}", x,  u)

v = asinh(x)
print string.Format("v = asinh({0}) = {1:F10}", x,  v)

print string.Format("cosh(u) = cosh({0:F10}) = {1}", u,  Math.Cosh(u))
print string.Format("sinh(v) = sinh({0:F10}) = {1}", v,  Math.Sinh(v))

/*
Output:
y = asin(-0.9) = -1.119769515
sin(y) = sin(-1.119769515) = -0.9

u = acosh(1.1) = 0.4435682544
v = asinh(1.1) = 0.9503469298
cosh(u) = cosh(0.4435682544) = 1.1
sinh(v) = sinh(0.9503469298) = 1.1
*/

 

 

Posted by Scripter
,


[파일명:  testSort.boo]------------------------------------------------
import System
import System.Collections

def printArray(arr as Array):
    Console.Write("[")
    for i in range(0, len(arr) - 1):
        s = "${arr[i]}, "
        Console.Write(s)
    if len(arr) > 0:
        Console.Write("{0}", "${arr[len(arr) - 1]}")
    Console.WriteLine("]")

arr = array(String, argv.Length)
for i in range(0,  argv.Length):
    arr[i] = argv[i]

Array.Sort(arr)
printArray(arr)
------------------------------------------------


실행> booi testSort.boo one two thee four five
[five, four, one, three, four]

실행> booi testSort.boo 하나 둘 셋 넷 다섯
[넷, 다섯, 둘, 셋, 하나]

 

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

콘솔에 삼각형

         *
       * *
      *   *
     *     *
    *       *
   *         *
  *           *
 *             *
*****************


을 출력하는 Boo 소스 코드를 작성해 보자. 이런 소스 코드의 작성은 학원이나 학교에서 프로그래밍 입문자에게 과제로 많이 주어지는 것 중의 하나이다. 코끼리를 보거나 만진 사람들이 저마다 그 생김새를 말할 때 제각기 다르게 표현할 수 있듯이 이런 소스 코드의 작성도 알고 보면 얼마든지 많은 방법이 있을 것이다. 여기서는 쉬운 코드 부터 작성해 보고 차츰차츰 소스를 바꾸어 가면서 Boo 프로그래밍의 기초부분을 터득해 보기로 한다.


Boo 언어는 프로그래밍은 다음 두 가지를 숙지하고 있으면 배우기 쉽다.

(1) 우선 Boo 언어의 문법과 구문 몸체는 Python의 것을 따른다.
     그러므로 들여쓰기 규칙을 Python 언어에서 처럼 꼭 지켜야 한다. 

(2)  그 다음 Boo 언어는 닷넷 상에서 동작하는 만큼
     (개념이나 함수 라이브러리 등) 내부적으로 C#의 것을 많이 따른다.


모든 소스 코드에서는 삼각형 출력 부분 담당 함수 printTriange()를 별도로 구현하였다.

우선 첫번 째 예제는 Boo의 컨솔 출력 매크로(함수) print의 사용법만 알면 누구나 코딩할 수 있는 매우 단순한 소스 코드이다. (파일 확장자만 py 대신 boo로 한 것이지 그 외에는 Python의 것과 완전 동일하다.)


삼각형 출력 예제 1
#  Filename: printTriangle1.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle1.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def printTriange():
    print "        *        "
    print "       * *       "
    print "      *   *      "
    print "     *     *     "
    print "    *       *    "
    print "   *         *   "
    print "  *           *  "
    print " *             * "
    print "*****************"

printTriange()




위의 소스 코드는 아무 알고리즘도 없는 너무 단순한 코드이다. 이런 코드를 작성했다간 출력 모양이나 크기를 변경해야 하는 상황을 맞이하면 워드프로세서로 문서 만드는 것 이상으로 많은 수작업을 하거나 아니면 포기하는 지경에 이를 수도 있다. 그래서 다음 처럼 좀 더 나은 소스 코드를 작성하였다. 빈칸을 출력할 것인지 별문자를 출력한 것인지를 결정하여 한 개의 문자씩 컨솔에 출력한다. 그런데 Boo 언어의 print 문은 Python 언어의 것 처럼 스트링을 출력 후 새 줄 문자(newline, '\n')을 추가한다. 그리고 끝에 콤마를 추가한

        print string,

문은 (Python 언어에서는 지원되자만) Boo 언어에서는 지원되지 않는다. Python 언어에서 sys.ㄴstdout.write(스트링) 에 해당하는 Boo 언어의 코드는 System.Console.Write(스트링) 이다.

따라서 Python 언어에서는

        import sys
        sys.stdout.write(string)

라고 코딩할 것을 Boo 언어로는

        import System
        Console.Write(string)

라고 코딩하였다.

아래의 소스 코드는 파일 확장자가 py 대신 boo로 바꾼 것 이외에, Python용 소스 코드에서

import sys

def write(s):
    sys.stdout.write(s)

라고 했던 것을 Boo용 소스 코드

import System

def write(s):
    Console.Write(s)

로 바꾼 것이 전부이다.



삼각형 출력 예제 2
#  Filename: printTriangle2.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle2.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

import System

def write(s):
    Console.Write(s)

def printTriange():
    for i in range(0, 8):
        for k in range(0, 8-i):
            write(" ")
        for k in range(0, 2*i+1):
            if k == 0 or k == 2*i:
                write("*")
            else:
                write(" ")
        for k in range(0, 8-i):
            write(" ")
        print

    for i in range(0, 17):
        write("*")
    print

printTriange()



위의 소스 코드는 Boo의 컨솔 출력 매크로 print 와 System.Console.Write() 그리고 for 반복 구문을 적절히 사용하여 구현되었다. 숫자 몇 곳만 수정하면 출력되는 삼각형의 크기를 바꿀 수 있다. 한 줄에 출력될 문자를 구성하는 알고리즘은 위의 예제와 근본적으로 같지만 print, System.Console.Write() 를 사용하지 않고, 그대신 문자의 리스트를 만들어 한 즐씩 출력하는 소스 코드를 다음 예제와 같이 작성해 보았다.
또 빈칸 17개의 문자로 구성된 리스트를 생성하기 위한 구문은

        whites = [" "]*17

이다. (string*number 또는 list*number 의 구문은 Python, Groovy, Ruby 언어에서도 지원된다.)

Python용 소스코드와 다른 것은 배열을 출력하는 Python 용 구문

    print "".join(line2)

대신 Boo용 코드

    print join(line2, "")

로 고친 곳이 두 곳이다.


리스트의 데이터들을 문자열로 연결하여 표현하기:
        Python용 소스 코드:  연결스트링.join(리스트)
            Boo용 소스 코드:  join(리스트, 연결스트링)



삼각형 출력 예제 3
#  Filename: printTriangle3.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle3.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def printTriange():
    line2 = [" "]*17
    for i in range(0, 8):
        line2 = [" "]*17
        line2[8-i] =  '*'
        line2[8+i] =  '*'
        print join(line2, "")

    line2 = [" "]*17
    for i in range(0, 17):
        line2[i] =  '*'
    print join(line2, "")

printTriange()




별(*) 문자를 이용하여 삼각형을 출력하는 일은 빈칸 문자와 별 문자응 적당한 좌표(위치)에 촐력하는 일이다. 출력될 한 줄의 스트링을 완성한 후 하나의 print 구문으로 출력하는 기법으로 소스 코드를 작성해 보았다. 소스 코드 중에

        whites = " "*17
        stars = "*"*17

은 지정된 개수(여기서는 17) 만큼 string을 중복 연결하는 구문이다.

Python 언어로 작성되었던 곳과 비교하면 형식화된 문자열 출력을 위해
Python 언어용 구문

        line2 = 포맷 % 데이터들

대신 Boo 언어용 구문(즉 C#에서 빌려온 구문)

        import System
        line2 = String.Format(포맷, 데이터들)

로 한 것이 다르다.



삼각형 출력 예제 4
#  Filename: printTriangle4.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle4.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

import System

def printTriange():
    whites = " "*17
    stars  = "*"*17
    line2 = String.Format("{0}{1}{2}", whites[0:8], "*", whites[0:7])
    print line2
    for i in range(1, 8):
        line2 = String.Format("{0}{1}{2}{3}", whites[:8-i], "*", whites[8-i:7+i], "*", whites[7+i:])
        print line2
    print stars

printTriange()




string은 immutable이라 그 내용을 변경할 수 없지만, 리스트는 그 요소(item)를 아무 때 나 변경할 수 있다. 한줄에 출력될 각 문자를 리스트 타입의 변수 line2에 저장한 다음 print 문으로 출력 시

    join(line2, "")

로 그 리스트의 모든 요소item)가 모두 연결되어 출력되게 하였다.



삼각형 출력 예제 5
#  Filename: printTriangle5.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle5.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def printTriange():
    whites = " "*17
    stars  = "*"*17
    start = 8
    line2 = [" "]*17
    line2[start] = "*"
    print join(line2, "")
    for i in range(1, 8):
        line2 = [" "]*17
        line2[start - i] = stars[start - i]
        line2[start + i] = stars[start + i]
        print join(line2, "")
    print stars

printTriange()




출력되는 삼각형이 좌우 대칭이라는 사실에 착안하여, 다음 소스 코드에서는  각 줄을 처음 8자, 중앙 한 문자, 끝 8자(처음 8자의 역순)로 string을 만들어 출력하였다.

Python용 소스 코드와 다른 것은 스트링을 거꾸로하는 reverse(스트링) 함수의 구현 뿐이다.

# Python용 reverse  함수
def reverse(chars):
    aa = array.array('c', chars)      # 스트링을 배열로 변환
    aa.reverse()                            # 배열을 역순으로
    return aa.tostring()                   # 역순으로된 배열을 스트링으로 변환하여 리턴
   
# Boo용 reverse  함수
def reverse(chars):                        # 스트링을 역순 List로 변환하여 
    return join(reversed(chars), "")    # 이 List의 요소들을 스트링으로 연결(join)하여 리턴



삼각형 출력 예제 6
#  Filename: printTriangle6.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle6.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def reverse(chars):
    return join(reversed(chars), "")
   
def printTriange():
    whites = " "*8
    stars  = "*"*8
    start = 8
    line = whites + '*' + whites
    print line
    for i in range(1, 8):
        line = whites[:-i] + '*' + whites[-i:-1]
        print line + ' ' + reverse(line)
    line = stars + '*' + stars
    print line

printTriange()




다음 소스 코드는 한 줄에 출력될 문자열의 데이터를 17비트 이진법 수로 구성하고, 이 이진법수의 비트가 0인 곳에는 빈칸을, 1인 곳에는 별(*)을 출력하는 기법으로 작성되었다.

아래의 소스는 Python용으로 만들어 둔 것을 조금 고쳐서 Boo용으로 바꾼 것이다.

Python용 소스 코드에서는

def itoa(num, radix=10):
    .............
    .............
 
로 작성된 진법변환 함수 itoa()의 정의가 Boo용 소스 코드에서는

def itoa(num as long, radix as int):
    .............
    .............

로 작성되었고, 또 리스트에 데이터를 추가하는 함수가 Python 소스 코드로는

    리스트.append(데이터)

이지만, Boo 소스 코드에서는

    리스트.Add(데이터)

이다.




삼각형 출력 예제 7
#  Filename: printTriangle7.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle7.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def itoa(num as long, radix as int):
   isNegative = false
   if num < 0:
      isNegative = true
      num = -num
   arr = []
   q, r = num, 0
   while q >= radix:
      r = q % radix
      q = q / radix
      arr.Add(BASE36[r])
   arr.Add(BASE36[q])
   if isNegative:
      arr.Add("-")
   return join(reversed(arr), '')

def printTriange():
    start = 0x100
    total = 0
    val = start
    data = ""
    for k in range(0, 8):
        val = (start << k) | (start >> k)
        data = itoa(val, 2)
        s = ""
        for i in range(0, 17 - len(data)):
            s += " "
        for i in range(0, len(data)):
            if "" + data[i] == '0':    // dara[i] is a type of char
                s += " "
            else:
                s += "*"
        print s
        total += val

    val = (start << 8) | (start >> 8)
    total += val
    data = itoa(total, 2)
    s = ""
    for i in range(0, 17 - len(data)):
        s += " "
    for i in range(0, len(data)):
        if data[i] == '0':
            s += " "
        else:
            s += "*"
    print s

printTriange()




기본적인 원리는 위의 소스 코드와 같지만 이진법수의 한 비트 마다 한 문자씩 츨력하는 대신에 출력될 한 줄의 string을 완성하여 이를 print 구문으로 출력하는 기법으로 재작성한 것이 다음의 소스 코드이다. anotherString = string.replace(원본, 타겟) 을 이용하여 모든 0을 빈칸으로, 모든 1을 별(*) 문자로 바꾸었으며, 별(*) 문자만으로 이루어진 마지막 줄 출력을 위해 변수 total을 준비하였다. for 반복 구문의 블럭 내에서 구문

            total |= val

이 하는 일이 무엇인지 이해할 수 있으면 좋겠다.

스트링을 역순으로 변환하는 함수 reverse()는 printTriangle6.boo 에서 작성된 것을 그대로 가져왔고, 정수를 지정된 진법(radix)의 스트링으로 변환하는 함수 itoa()는 printTriangle8.boo 에서 작성된 것을 그대로 가져왔다. 그리고 printTriangle()의 구현부에서는 Python용 소스 printTriangle8.py
에 있던 것에서 스트링 치환 메소드 string.replace(oldString, newString) 대신 string.Replace(oldString, newString) (즉, 소문자 r을 대문자 R)로 바꾼 것만 다르다.




삼각형 출력 예제 8
#  Filename: printTriangle8.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle8.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def reverse(chars):
    return join(reversed(chars), "")
   
BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def itoa(num as long, radix as int):
   isNegative = false
   if num < 0:
      isNegative = true
      num = -num
   arr = []
   q, r = num, 0
   while q >= radix:
      r = q % radix
      q = q / radix
      arr.Add(BASE36[r])
   arr.Add(BASE36[q])
   if isNegative:
      arr.Add("-")
   return join(reversed(arr), '')

def printTriange():
    zeros  = "00000000"
    start = 0x100
    total = 0
    val = start
    line = ""
    data = ""
    for k in range(0, 8):
        val = (start << k) | (start >> k)
        data = itoa(val, 2)
        line = zeros[0:17-len(data)] + data
        line = line.Replace("0", " ")
        line = line.Replace("1", "*")
        print line
        total |= val

    val = (start << 8) | (start >> 8)
    total |= val
    line = itoa(total, 2)
    line = line.Replace("0", " ")
    line = line.Replace("1", "*")
    print line

printTriange()




소스 코드가 처음 것 보다 매우 복잡해졌지만, Boo의 리스트를 이용해서 구현해 보았다. Boo 언어 외에 Python, Groovy, Ruby 언어 같은 스크립팅 언어에서도 리스트와 맵은 매우 중요하게 취급되며, 구문에서도 이를 위한 문법을 제공하고 있다. 별(*) 문자만으로 구성된 마지막 줄 출력을 위해 리스트 타입의 변수 last를 준비하였다. 또 리스트에 속한 모든 item을 출력하는 Boo 소스 코드

        print join(data, "")

는 Python 소스 코드에서는

        print "".join(data)

로 작성되었던 것을 Boo용으로 수정한 것이다.



삼각형 출력 예제 9
#  Filename: printTriangle9.boo
#            Print a triangle on console.
#
#  Execute: python printTriangle9.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

def printTriange():
    start = 8
    data = [" "]*17
    last = [" "]*17

    data[start] = "*"
    last[start] = "*"
    print join(data, "")
    data[start] = " "

    for k in range(1, 8):
        data[start - k] = "*"
        last[start - k] = "*"
        data[start + k] = "*"
        last[start + k] = "*"
        print join(data, "")
        data[start - k] = " "
        data[start + k] = " "

    last[start - 8] = "*"
    last[start + 8] = "*"
    print join(last, "")

printTriange()





다음 예제는 수학에서 xy-좌표평면에 점을 찍듯이 논리 구문

             (x + y - 8 == 0) or (y - x + 8 == 0) or (y - 8 == 0)

가 참이 되는 위치에 별(*) 문자를 표시하는 기법으로 작성된 소스 코드이다.

Python용 소스 코드에서는

    sys.stdout.write(스트링)

이라고 작성했던 것을 Boo용 소스 코드에서는

    System.Console.Write(스트링)

이라고 작성한 것이 다르다.




삼각형 출력 예제 10
#  Filename: printTriangle10.boo
#            Print a triangle on console.
#
#  Execute: booi printTriangle10.boo
#
#      Date:  2009/04/08
#    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

import System

def printTriange():
    for y in range(0, 9):
        for x in range(0, 17):
            if (x + y - 8 == 0) or (y - x + 8 == 0) or (y - 8 == 0):
                a = '*'
            else:
                a = ' '
            Console.Write(a)
        print

printTriange()





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

 


Posted by Scripter
,

Boo 언어에서도 한 개의 소스 파일에 여러 개의 클래스가 존재해도 된다. 또 클래스명과 다른 파일명으로 저장해도 된다. Boo 언어의 구뮨 몸체는 Python 언어에서 빌려왔지만, Python 언어는 동적 타이핑(즉 변수의 타입이 실행시 결정되는) 언어, Boo 언어는 정적 타이핑(즉 변수의 타입이 컴파일시 결정되는) 언어라는 점이 다르다.
또한 Boo  언어는 닷넷환경에서 동작하는 만큼 내부적으로는 C# 언어에서 사용하는 개념들을 내포하고 있다.

다음은 두 개의 클래스로 구성되어 있다.
Parent는 부모 클래스이고 Child는 Parent에서 상속 받은 자식 클래스이다.


class Parent:
    _name as string
    def constructor():       # 클래스 생성자. 이것이 있어야 서브클래싱을 할 수 있다.
        pass
    def constructor(name as string):       # 클래스 생성자
        _name = name
    def sayName():
        print("I am Parent, " + _name)

class Child(Parent):        # 부모 클래스 상속
    def constructor(name as string):
        _name = name
    def sayName():
        print("I am a child, named as " + _name)

obj as Child = Child("Dooly")        # 클래스 생성
obj.sayName()



실행> booi testSubclassing.boo
I am a child, named as Dooly



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

 

Posted by Scripter
,


초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 Boo 소스이다.

소스 코드는 Python 언어로 작성된 것과 거의 같다. 단지 여기서는 스트링을 int 타입이나 long 타입으로 변환하는 구문만 언급한다.

        int.Parse(스트링)         // 스트링을 int 타입으로 변환하기
        long.Parse(스트링)      // 스트링을 long 타입으로 변환하기

# Filename: makeMultTable.boo
#
#     Print a multiplication table.
#
#     Execute: booi makeMultTable.boo 230 5100
#
#    Date:  2009/04/04
#  Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]

import System

def printUsing():
    print "Using: booi makeMultTable.boo [number1] [number2]"
    print "Print a multiplication table for the given two integers."

def printMultTable(x as long, y as long):
    nx as long = x
    if nx < 0:
        nx = -nx
    ny as long = y
    if ny < 0:
        ny = -ny
    ntail1 as int = 0
    ntail2 as int = 0
    while nx % 10 == 0:
        nx = nx / 10
        ntail1 = ntail1 + 1
    while ny % 10 == 0:
        ny = ny / 10
        ntail2 = ntail2 + 1
    z = nx * ny
    strZ = "" + z
    strX = "" + nx
    strY = "" + ny
    n = len(strY)
    zeros  = "0000000000000000000000000000000000000000"
    whites = "                                        "
    bars   = "----------------------------------------"
    loffset = "       "
    line4 = loffset + strZ
    line1 = loffset + whites[0: len(strZ) - len(strX)] + strX
    line2 = "   x ) " +  whites[0: len(strZ) - len(strY)] + strY
    line3 = "     --" +  bars[0: len(strZ)]
    print line1 + zeros[0: ntail1]
    print line2 + zeros[0: ntail2]
    print line3
    if len(strY) > 1:
        for i in range(0, len(strY)):
            y1 = int.Parse(strY[len(strY) - i - 1: len(strY) - i])
            if y1 != 0:
                strT = "" + (nx * y1)
                print loffset + whites[0: len(strZ) - len(strT) - i] + strT
        print line3
    print line4 + zeros[0: ntail1] + zeros[0: ntail2]

if len(argv) >= 2:
    x = long.Parse(argv[0])
    y = long.Parse(argv[1])
    print
    printMultTable(x, y)
else:
    printUsing()



실행> python makeMultTable.py 230 5100
결과>

         230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

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

 

Posted by Scripter
,
Boo 언어에서 주로 쓰이는  컨솔 출력 구문

         print  something

은 새 줄 문자(newline code '\n')도 출력한다. 파이썬 언어에서 쓰이는 (끝에 콤마가 붙은) 구문

         print  something.

은 Boo  언어에서는 지원하지 않는다.

그렇다면 새 줄 문자(newline code '\n')를 출력하지 않는 출력 구문은 없을까?
Boo 언어 자체에서는 지원하지 않으므로, 닷넷의 System.Console.Write(스트링) 을 발려서 쓰는 방법이 있다.

        import System
        for i in range(10): Console.Write("*")
        Console.Write("\n")

        **********
를 출력한다.


 

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

Posted by Scripter
,
▒ Boo 소스:  testStringReverse.boo

/*
 * Filename: testStringReverse.boo
 *
 *    [참고] 이 파일은 UTF-8 인코딩으로 저장되어야 함.
 *
 *  Compile: booc -utf8 testStringReverse.boo
 *  Execute: testStringReverse
 */

s = "Hello, world!"
s2 = "안녕하세요?"

#########################################
u = join(reversed(s), '')     # 문자열 거꾸로 하기
u2 = join(reversed(s2), '')   # 문자열 거꾸로 하기

print( "s = " + s )
print( " ---> " + "join(reversed(s), '') = " + u )
print( "s2 = " + s2 )
print( " ---> " + "join(reversed(s2), '') = " + u2 )
#########################################
# 출력 결과
# s = Hello, world!
#  ---> join(reversed(s), '') = !dlrow ,olleH
# s2 = 안녕하세요?
#  ---> join(reversed(s2), '') = ?요세하녕안




한글이 포함된 Boo  언어 소스코드는 반드시 UTF-8 인코딩으로 저장되어야 하고, booc 명령으로 컴파일할 때 -utf8 옵션을 주어야 한다.

 

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

 
Posted by Scripter
,

ASCII(애스키)란 American Standard Code for Information Interchange의 줄임글로서, 영문자에 기초한 문자 인코딩이다.  이 문자 인코딩에는 C0 제어문자(C0 control character)도 포함되어 있다.  ( 참고:  ASCII - Wikipedia, the free encyclopedia )

다음은  7bit ASCII 코드표를 만들어 보여주는 Boo 소스 코드이다. 소스 코드 중에 진법변환에 필요한 함수

        convertAtoI(string, radix)
        convertItoA(number, radix)

의 구현도 포함되어 있다. 소스코드의 170째 줄에
 
        c = cast(char, j*16 + i)    // casting from int to char

로 작성된 것은 식 j*16 + i 로 계산된 int 값을 char 타입으로 캐스팅하는 장면이다. 참고로 C/C++/Java 언어라면
 
        c = (char) (j*16 + i)     // casting from int to char

로 작성되었울 것이다. 일반적으로 Boo 언어에서 캐스팅하는 구문은
 
           변수명 = cast(새타입, 식)
이다.



  1. #  Filename: makeAsciiTable.boo
  2. #            Make a table of ascii codes.
  3. #
  4. #  Execute: booi makeAsciiTable.boo
  5. #
  6. #      Date:  2009/04/04
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import System
  9. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10. def println(s as string):
  11.     print(s)
  12. def printUsage():
  13.     println("Usage: booi makeAsciiTable.boo")
  14.     println("Make a table of ascii codes.")
  15. def convertItoA(num as long, radix as int) as string:
  16.     isNegative = false
  17.     if num < 0:
  18.         isNegative = true
  19.         num = -num
  20.     arr as string = ""
  21.     q as long = num
  22.     r as long = 0
  23.     while q >= radix:
  24.         r = q % radix
  25.         q = q / radix
  26.         arr += BASE36[r]
  27.     arr += BASE36[q]
  28.     if isNegative:
  29.         arr += "-"
  30.     s as string = ""
  31.     n = len(arr)
  32.     for i as int in range(n):
  33.         s += arr[n - 1 - i]
  34.     return s
  35. def toAscii(s as String) as int:
  36.     objAscii as System.Text.ASCIIEncoding = System.Text.ASCIIEncoding()
  37.     val as System.Byte = objAscii.GetBytes(s)[0]
  38.     return Convert.ToInt32(val)
  39. def convertAtoI(srcStr as string, radix as int) as long:
  40.     isNegative = false
  41.     ret as long = 0L
  42.     m = len(srcStr)
  43.     val = 0
  44.     c = srcStr[0:1]
  45.     if toAscii(c) == toAscii('-'):
  46.         isNegative = true
  47.     elif toAscii(c) >= toAscii('0') and toAscii(c) <= toAscii('9'):
  48.         ret = toAscii(c) - toAscii('0')
  49.     elif toAscii(c) >= toAscii('A') and toAscii(c) <= toAscii('Z'):
  50.         ret = (toAscii(c) - toAscii('A')) + 10
  51.     elif toAscii(c) >= toAscii('a') and toAscii(c) <= toAscii('z'):
  52.         ret = (toAscii(c) - toAscii('a')) + 10
  53.     if ret >= radix:
  54.         raise Exception("        invalid character!")
  55.         return ret
  56.     for i in range(1, m):
  57.         c = srcStr[i:i+1]
  58.         ret *= radix
  59.         if toAscii(c) >= char('0') and toAscii(c) <= char('9'):
  60.             val = toAscii(c) - toAscii('0')
  61.         elif toAscii(c) >= char('A') and toAscii(c) <= char('Z'):
  62.             val = (toAscii(c) - toAscii('A')) + 10
  63.         elif toAscii(c) >= char('a') and toAscii(c) <= char('z'):
  64.             val = (toAscii(c) - toAscii('a')) + 10
  65.         if val >= radix:
  66.             raise Exception("        invalid character!")
  67.             return ret
  68.         ret += val
  69.     return ret
  70. asc as List = [
  71.     "NUL", "SOH", "STX", "ETX", "EOT",
  72.     "ENQ", "ACK", "BEL", "BS", "HT",
  73.     "LF", "VT", "FF", "CR", "SO",
  74.     "SI", "DLE", "DC1", "DC2", "DC3",
  75.     "DC4", "NAK", "SYN", "ETB", "CAN",
  76.     "EM", "SUB", "ESC", "FS", "GS",
  77.     "RS", "US", "Spc"
  78. ]
  79. control as List = [
  80.     "NUL (null)",
  81.     "SOH (start of heading)",
  82.     "STX (start of text)",
  83.     "ETX (end of text)",
  84.     "EOT (end of transmission)",
  85.     "ENQ (enquiry)",
  86.     "ACK (acknowledge)",
  87.     "BEL (bell)",
  88.     "BS  (backspace)",
  89.     "TAB (horizontal tab)",
  90.     "LF  (line feed, NL new line)",
  91.     "VT  (vertical tab)",
  92.     "FF  (form feed, NP new page)",
  93.     "CR  (carriage return)",
  94.     "SO  (shift out)",
  95.     "SI  (shift in)",
  96.     "DLE (data link escape)",
  97.     "DC1 (device control 1)",
  98.     "DC2 (device control 2)",
  99.     "DC3 (device control 3)",
  100.     "DC4 (device control 4)",
  101.     "NAK (negative acknowledge)",
  102.     "SYN (synchronous idle)",
  103.     "ETB (end of trans. block)",
  104.     "CAN (cancel)",
  105.     "EM  (end of medium)",
  106.     "SUB (substitute, EOF end of file)",
  107.     "ESC (escape)",
  108.     "FS  (file separator)",
  109.     "GS  (group separator)",
  110.     "RS  (record separator)",
  111.     "US  (unit separator)",
  112. ]
  113. def makeTable():
  114.     sbuf = ""
  115.     abuf = ""
  116.     tbuf = ""
  117.     sbuf = "    "
  118.     for i in range(0, 8):
  119.         sbuf += "+----"
  120.     sbuf += "+"
  121.     println(sbuf)
  122.     sbuf = "    "
  123.     sbuf += "| 0- "
  124.     sbuf += "| 1- "
  125.     sbuf += "| 2- "
  126.     sbuf += "| 3- "
  127.     sbuf += "| 4- "
  128.     sbuf += "| 5- "
  129.     sbuf += "| 6- "
  130.     sbuf += "| 7- "
  131.     sbuf += "|"
  132.     println(sbuf)
  133.     sbuf = "+---"
  134.     for i as int in range(0, 8):
  135.         sbuf += "+----"
  136.     sbuf += "+" 
  137.     println(sbuf)
  138.     for i as int in range(0, 16):
  139.         tbuf = ""
  140.         sbuf = convertItoA(i, 16)
  141.         tbuf += "| " + sbuf + " "
  142.         for j as int in range(0, 8):
  143.             k as int = j*16 + i
  144.             if j*16 + i <= 32:
  145.                 abuf = string.Format("| {0,-3}", asc[j*16 + i])
  146.             elif j*16 + i == 127:
  147.                 abuf = string.Format("| {0,-3}", "DEL")
  148.             else:
  149.                 c = cast(char, j*16 + i)    // casting from int to char
  150.                 abuf = string.Format("| {0,2} ", c)
  151.             tbuf += abuf
  152.         tbuf += "|"
  153.         println(tbuf)
  154.     sbuf = "+---"
  155.     for i in range(0, 8):
  156.         sbuf += "+----"
  157.     sbuf += "+"
  158.     println(sbuf)
  159.     println("")
  160.     for i in range(0, 16):
  161.         tbuf = string.Format("{0,-30}  {1,-34}", control[i], control[i+16])
  162.         println(tbuf)
  163. if len(argv) > 1 and "-h" == argv[0]:
  164.     printUsage()
  165.     Environment.Exit(1)
  166. makeTable()



실행> booi makeAsciiTable.boo

    +----+----+----+----+----+----+----+----+
    | 0- | 1- | 2- | 3- | 4- | 5- | 6- | 7- |
+---+----+----+----+----+----+----+----+----+
| 0 | NUL| DLE| Spc|  0 |  @ |  P |  ` |  p |
| 1 | SOH| DC1|  ! |  1 |  A |  Q |  a |  q |
| 2 | STX| DC2|  " |  2 |  B |  R |  b |  r |
| 3 | ETX| DC3|  # |  3 |  C |  S |  c |  s |
| 4 | EOT| DC4|  $ |  4 |  D |  T |  d |  t |
| 5 | ENQ| NAK|  % |  5 |  E |  U |  e |  u |
| 6 | ACK| SYN|  & |  6 |  F |  V |  f |  v |
| 7 | BEL| ETB|  ' |  7 |  G |  W |  g |  w |
| 8 | BS | CAN|  ( |  8 |  H |  X |  h |  x |
| 9 | HT | EM |  ) |  9 |  I |  Y |  i |  y |
| A | LF | SUB|  * |  : |  J |  Z |  j |  z |
| B | VT | ESC|  + |  ; |  K |  [ |  k |  { |
| C | FF | FS |  , |  < |  L |  \ |  l |  | |
| D | CR | GS |  - |  = |  M |  ] |  m |  } |
| E | SO | RS |  . |  > |  N |  ^ |  n |  ~ |
| F | SI | US |  / |  ? |  O |  _ |  o | DEL|
+---+----+----+----+----+----+----+----+----+

NUL (null)                      DLE (data link escape)
SOH (start of heading)          DC1 (device control 1)
STX (start of text)             DC2 (device control 2)
ETX (end of text)               DC3 (device control 3)
EOT (end of transmission)       DC4 (device control 4)
ENQ (enquiry)                   NAK (negative acknowledge)
ACK (acknowledge)               SYN (synchronous idle)
BEL (bell)                      ETB (end of trans. block)
BS  (backspace)                 CAN (cancel)
TAB (horizontal tab)            EM  (end of medium)
LF  (line feed, NL new line)    SUB (substitute, EOF end of file)
VT  (vertical tab)              ESC (escape)
FF  (form feed, NP new page)    FS  (file separator)
CR  (carriage return)           GS  (group separator)
SO  (shift out)                 RS  (record separator)
SI  (shift in)                  US  (unit separator)




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

컴퓨터 프로그래밍에서 꼭 알아두어야 할 주요 진법은 당연히 10진법, 2진법, 8진법, 16진법이다.
다음은  0 에서 15 까지의 정수를 10진법, 2진법, 8진법, 16진법의 표로 만들어 보여주는 Boo 소스 코드이다. 진법 변환에 필요한 함수

        convertAtoI(string, radix)
        convertItoA(number, radix)

를 Boo 코드로 자체 작성하여 사용하였다.



  1. #  Filename: makeRadixTable.boo
  2. #            Show the radix table with 10-, 2-, 8-, 16-radices.
  3. #
  4. #  Execute: booi makeRadixTable.boo
  5. #
  6. #      Date:  2009/04/03
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. import System
  9. BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  10. def println(s as string):
  11.     print(s)
  12. def printUsage():
  13.     println("Usage: booi makeRadixTable.boo")
  14.     println("Show the radix table with 10-, 2-, 8-, 16-radices.")
  15. def convertItoA(num as long, radix as int) as string:
  16.     isNegative = false
  17.     if num < 0:
  18.         isNegative = true
  19.         num = -num
  20.     arr as string = ""
  21.     q as long = num
  22.     r as long = 0
  23.     while q >= radix:
  24.         r = q % radix
  25.         q = q / radix
  26.         arr += BASE36[r]
  27.     arr += BASE36[q]
  28.     if isNegative:
  29.         arr += "-"
  30.     s as string = ""
  31.     n = len(arr)
  32.     for i as int in range(n):
  33.         s += arr[n - 1 - i]
  34.     return s
  35. def toAscii(s as String) as int:
  36.     objAscii as System.Text.ASCIIEncoding = System.Text.ASCIIEncoding()
  37.     val as System.Byte = objAscii.GetBytes(s)[0]
  38.     return Convert.ToInt32(val)
  39. def convertAtoI(srcStr as string, radix as int) as long:
  40.     isNegative = false
  41.     ret as long = 0L
  42.     m = len(srcStr)
  43.     val = 0
  44.     c = srcStr[0:1]
  45.     if toAscii(c) == toAscii('-'):
  46.         isNegative = true
  47.     elif toAscii(c) >= toAscii('0') and toAscii(c) <= toAscii('9'):
  48.         ret = toAscii(c) - toAscii('0')
  49.     elif toAscii(c) >= toAscii('A') and toAscii(c) <= toAscii('Z'):
  50.         ret = (toAscii(c) - toAscii('A')) + 10
  51.     elif toAscii(c) >= toAscii('a') and toAscii(c) <= toAscii('z'):
  52.         ret = (toAscii(c) - toAscii('a')) + 10
  53.     if ret >= radix:
  54.         raise Exception("        invalid character!")
  55.         return ret
  56.     for i in range(1, m):
  57.         c = srcStr[i:i+1]
  58.         ret *= radix
  59.         if toAscii(c) >= char('0') and toAscii(c) <= char('9'):
  60.             val = toAscii(c) - toAscii('0')
  61.         elif toAscii(c) >= char('A') and toAscii(c) <= char('Z'):
  62.             val = (toAscii(c) - toAscii('A')) + 10
  63.         elif toAscii(c) >= char('a') and toAscii(c) <= char('z'):
  64.             val = (toAscii(c) - toAscii('a')) + 10
  65.         if val >= radix:
  66.             raise Exception("        invalid character!")
  67.             return ret
  68.         ret += val
  69.     return ret
  70. def makeTable():
  71.     sbuf = ""
  72.     abuf = ""
  73.     tbuf = ""
  74.     for i in range(0, 4):
  75.         sbuf += "+-------"
  76.     sbuf += "+"
  77.     println(sbuf)
  78.     sbuf = "|  Dec"
  79.     sbuf += "\t|   Bin"
  80.     sbuf += "\t|  Oct"
  81.     sbuf += "\t|  Hex  |"
  82.     println(sbuf)
  83.     sbuf = ""
  84.     for i in range(0, 4):
  85.         sbuf += "+-------"
  86.     sbuf += "+"
  87.     println(sbuf)
  88.     for i in range(0, 16):
  89.         sbuf = string.Format("|   {0,2}", i)
  90.         abuf = convertItoA(i, 2)
  91.         tbuf = string.Format("\t|  {0,4}", abuf)
  92.         sbuf += tbuf
  93.         abuf = convertItoA(i, 8)
  94.         tbuf = string.Format("\t|   {0,2}", abuf)
  95.         sbuf += tbuf
  96.         abuf = convertItoA(i, 16)
  97.         tbuf = string.Format("\t|    {0,-2} |", abuf)
  98.         sbuf += tbuf
  99.         println(sbuf)
  100.     sbuf = ""
  101.     for i in range(0, 4):
  102.         sbuf += "+-------"
  103.     sbuf += "+"
  104.     println(sbuf)
  105. if len(argv) > 0 and "-h" == argv[0]:
  106.     printUsage()
  107.     Environment.Exit(1)
  108. makeTable()



실행> booi makeRadixTable.boo

+-------+-------+-------+-------+
|  Dec  |   Bin |  Oct  |  Hex  |
+-------+-------+-------+-------+
|    0  |     0 |    0  |    0  |
|    1  |     1 |    1  |    1  |
|    2  |    10 |    2  |    2  |
|    3  |    11 |    3  |    3  |
|    4  |   100 |    4  |    4  |
|    5  |   101 |    5  |    5  |
|    6  |   110 |    6  |    6  |
|    7  |   111 |    7  |    7  |
|    8  |  1000 |   10  |    8  |
|    9  |  1001 |   11  |    9  |
|   10  |  1010 |   12  |    A  |
|   11  |  1011 |   13  |    B  |
|   12  |  1100 |   14  |    C  |
|   13  |  1101 |   15  |    D  |
|   14  |  1110 |   16  |    E  |
|   15  |  1111 |   17  |    F  |
+-------+-------+-------+-------+



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