값과 메서드
값은 문자열, 숫자, 불리언, 리스트, 맵, 날짜, 함수, null, 그리고 패키지가 추가하는 값(파일, HTTP 응답)입니다. 모든 값에는 메서드가 있으며, ->로 호출하고 연결할 수 있습니다:
<echo>{ $name->trim()->upper() }</echo>
<echo>{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }</echo>
<echo>{ $people |> sort(by: .name) |> first() }</echo>
<echo>{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }</echo>echo "{ $name->trim()->upper() }"
echo "{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }"
echo "{ $people |> sort(by: .name) |> first() }"
echo "{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }"pluck(key)를 사용하면 각 항목에서 순서대로 필드를 읽을 수 있습니다. pluck에 키 목록을 주면 항목마다 새 맵을 하나씩 만듭니다. 키는 따옴표 없는 이름, 따옴표로 감싼 문자열, 또는 변수일 수 있습니다.
<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<let name="names" value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<let name="cards" value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] -->
<let name="labels" value="$people->pluck(['name'])" /> <!-- [{ name: 'Joan' }, { name: 'Sam' }] -->$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
$names = $people->pluck(name) // ['Joan', 'Sam']
$cards = $people->pluck([name, age]) // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }]
$labels = $people->pluck(['name']) // [{ name: 'Joan' }, { name: 'Sam' }]맵에 없는 키는 null을 줍니다. 타입이 있는 레코드는 평소의 필드 검사를 유지합니다. 빈 입력 리스트는 []를 주고, pluck([])는 입력 항목마다 빈 맵을 하나씩 줍니다. 반복된 키는 요청한 순서대로 한 번만 나타납니다.
리스트에서 contains(value), index_of(value), remove(value), count_of(value)는 ==로 비교합니다. 예를 들어 [1, '1']->count_of(1)는 2을 줍니다. unique()는 엄격한 동등성(===)을 사용하므로 [1, '1']->unique()는 두 항목을 모두 유지합니다.
is_empty()은 문자열에서는 문자 0개, 리스트에서는 항목 0개, 맵에서는 키 0개를 뜻합니다. 공백만 있는 입력도 허용하려고 $text->is_empty()를 사용했다면, 그 동작을 유지하려면 $text->is_blank()를 사용하세요.
| Text | ->is_empty() |
->is_blank() |
|---|---|---|
'' |
true |
true |
' ' |
false |
true |
'hello' |
false |
false |
숫자는 항상 지수 표기 없이 일반 숫자로 씁니다: echo 10 ** 20는 100000000000000000000를 출력하고, echo 0.1 ** 20는 0.00000000000000000001를 출력합니다. 정수는 크기에 상관없이 정확합니다: 123456789 * 987654321는 121932631112635269, 2 ** 100는 1267650600228229401496703205376이며, 텍스트나 JSON에서 읽은 20자리 id도 모든 자릿수를 유지합니다. +, -, *, %, **, /(나누어떨어질 때), ->sum(), ->product(), @gcd, @lcm, @factorial는 모두 정확하게 유지됩니다. 소수, @sqrt 등은 일반 부동소수점으로 동작합니다. 소수는 유효숫자 15자리까지 보여 주므로 0.1 + 0.2는 0.3를 출력합니다. 정수는 약 30,000자리까지 커질 수 있으며, 그 이상이면 Limit 오류로 멈춥니다.
텍스트에서 ->count()과 위치(->slice(), ->index_of(), $text[0]에서 쓰는)는 대부분의 문자를 한 자리로, 이모지 같은 문자는 두 자리로 셉니다. 어떤 메서드도 그런 문자를 반으로 자르지 않습니다: ->chars(), ->first(), ->last(), ->reverse()는 독자가 보는 대로 온전한 문자 단위로 동작하며, ->slice()와 ->truncate()는 그 안에 떨어질 자르기 지점을 그 앞으로 옮깁니다.
값에 관한 단순한 사실은 필드이며, 맵의 키와 같은 방식으로 점을 쓰고 괄호 없이 읽습니다:
<import package="KScript.IO" />
<let name="day" value="'2026-11-19'->to_date()" />
<let name="file" value="@file(./notes.txt)" />
<echo>{ $day.year } { $day.weekday } { $file.name } { $file.size }</echo>import KScript.IO
$day = '2026-11-19'->to_date()
$file = @file(./notes.txt)
echo "{ $day.year } { $day.weekday } { $file.name } { $file.size }"따라서 $response.status, $file.size, $url.host, $e.status는 필드이고, 인수를 받거나 작업을 수행하는 것은 메서드입니다: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). 참 또는 거짓을 답하는 이름은 is_ 또는 has_로 시작합니다: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).
시간의 길이는 기간입니다. 숫자와 따옴표 없는 단위로 쓰며, 예를 들어 500ms, 30s, 10m, 2h, 1d, 1w이고, 여러 단위를 이어 붙일 수도 있습니다(1h30m). 시간 길이를 받는 것은 모두 기간을 받습니다: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). 단순한 숫자는 항상 초입니다.
년과 월은 y과 mo이며(m는 분입니다): 1y, 6mo, 5y10mo. 월이나 년은 고정된 길이가 없으므로, 이들은 달력 기준으로 날짜를 옮기며($date + 1mo는 가능한 경우 일자를 유지합니다), wait(1mo)나 1mo.hours처럼 고정 길이가 필요한 곳에서는 거부됩니다.
편집기는 각 타입의 필드와 메서드를 자동 완성하고 그 기능을 보여 줍니다. 값의 형식을 바꾸려면, 예를 들어 JSON 텍스트를 읽거나 행을 CSV로 쓰려면 ->convert()를 사용하세요: 형식 간 변환을 보세요.
날짜
날짜의 달력 정보는 필드입니다: .year, .month, .day, .weekday, .quarter, .day_of_year, .week(ISO 주차 번호), .days_in_month. .is_past, .is_future, .is_today, .is_weekend는 날짜를 현재와 비교하므로 템플릿에 적합합니다:
<let name="post" value="{ title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }" />
<echo value="$post.published_at.is_future ? 'Coming soon' : $post.title" />$post = { title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }
echo $post.published_at.is_future ? 'Coming soon' : $post.title->start_of(unit)와 ->end_of(unit)는 날짜가 속한 day, week, month, quarter, 또는 year의 첫 순간과 마지막 순간을 줍니다. 이는 '이번 달 주문'이라는 보고서에 필요한 것입니다. 주는 로캘의 첫 요일로 시작합니다(en-GB에서는 월요일, en-US에서는 일요일), 또는 week_start:가 지정한 요일로 시작합니다:
<let name="now" value="'2026-11-19 14:30'->to_date()" />
<let name="from" value="$now->start_of(month)" /> <!-- 2026-11-01 00:00 -->
<let name="to" value="$now->end_of(month)" /> <!-- 2026-11-30 23:59:59 -->
<let name="monday" value="$now->start_of(week, week_start: monday)" /> <!-- 2026-11-16 -->$now = '2026-11-19 14:30'->to_date()
$from = $now->start_of(month) // 2026-11-01 00:00
$to = $now->end_of(month) // 2026-11-30 23:59:59
$monday = $now->start_of(week, week_start: monday) // 2026-11-16달력 연산은 온전한 단위를 셉니다. $date + 1y6mo는 날짜를 년과 월만큼 옮기며, ->add()도 그렇게 하는데, 이것은 years:, months:, weeks:, days:의 어떤 조합도 받습니다(->subtract()는 뒤로 옮깁니다). 월은 가능한 경우 일자를 유지하므로, 1월 31일에 한 달을 더하면 2월의 마지막 날이 됩니다. 시간과 분은 기간을 더하거나 빼서 다룹니다:
<let name="due" value="'2026-11-30'->to_date()->add(months: 1, days: 2)" /> <!-- 2027-01-01 -->
<let name="last_week" value="@today()->subtract(weeks: 1)" />
<let name="renewal" value="'2026-01-31'->to_date() + 1y1mo" /> <!-- 2027-02-28 -->
<let name="meeting" value="'2026-11-30 09:00'->to_date() + 1h30m" /> <!-- 10:30 -->$due = '2026-11-30'->to_date()->add(months: 1, days: 2) // 2027-01-01
$last_week = @today()->subtract(weeks: 1)
$renewal = '2026-01-31'->to_date() + 1y1mo // 2027-02-28
$meeting = '2026-11-30 09:00'->to_date() + 1h30m // 10:30날짜는 기간으로만 옮길 수 있습니다. $date + 1는 오류인데, 다른 곳에서는 단순한 숫자가 항상 초를 뜻하기 때문이며, 불리언, 리스트, 또 다른 날짜를 더하는 것도 마찬가지입니다. 단위를 쓰세요($date + 3d). 숫자가 날짜를 뜻하는 유일한 곳은 1970년 이후의 초 단위인 Unix 타임스탬프이며, ->to_date()는 이를 읽고 ->timestamp()는 이를 돌려줍니다:
<let name="created" value="1795996800->to_date()" /> <!-- 2026-11-30 00:00 UTC -->
<let name="seconds" value="$created->timestamp()" /> <!-- 1795996800 -->$created = 1795996800->to_date() // 2026-11-30 00:00 UTC
$seconds = $created->timestamp() // 1795996800한 날짜에서 다른 날짜를 빼면 그 사이의 정확한 시간이 기간으로 나옵니다. ->since(other, in: unit)는 대신 생일처럼 온전한 일, 주, 월, 년 수를 셉니다. ->is_same(other, unit)는 두 날짜가 같은 날(기본값), 주, 월, 분기, 년에 속하는지 묻습니다:
<let name="start" value="'2026-11-30 09:00'->to_date()" />
<let name="took" value="'2026-11-30 10:30'->to_date() - $start" /> <!-- 1h30m -->
<let name="born" value="'1990-12-01'->to_date()" />
<let name="age" value="'2026-11-19'->to_date()->since($born, in: years)" /> <!-- 35 -->
<let name="same" value="@today()->is_same(@now(), day)" /> <!-- true -->$start = '2026-11-30 09:00'->to_date()
$took = '2026-11-30 10:30'->to_date() - $start // 1h30m
$born = '1990-12-01'->to_date()
$age = '2026-11-19'->to_date()->since($born, in: years) // 35
$same = @today()->is_same(@now(), day) // truenow는 컴퓨터의 시계에서 가져오므로, 테스트에서는 @with_clock(date, fn)이 @now(), @today(), 위의 필드들, 그리고 @format_relative()에 대해 그 시각을 고정합니다.
텍스트 다루기
텍스트에는 자주 반복되는 작업을 위한 도우미가 있습니다. 이름의 대소문자를 바꾸기, 구분자에서 자르기, 공백 정리하기, 페이로드에 서명하기입니다.
<echo value="'Order Total'->case(snake)" /> <!-- order_total -->
<echo value="'order_total'->case(camel)" /> <!-- orderTotal -->
<echo value="'order total'->case(pascal)" /> <!-- OrderTotal -->
<echo value="'orderTotal'->case(kebab)" /> <!-- order-total -->
<let name="email" value="'joan@example.com'" />
<echo>{ $email->before('@') } at { $email->after('@') }</echo> <!-- joan at example.com -->
<echo value="'archive.tar.gz'->after('.', last)" /> <!-- gz -->
<echo value="' too many spaces '->squish()" /> <!-- too many spaces -->
<let name="words" value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="'4242424242424242'->mask('*', keep_end: 4)" />echo 'Order Total'->case(snake) // order_total
echo 'order_total'->case(camel) // orderTotal
echo 'order total'->case(pascal) // OrderTotal
echo 'orderTotal'->case(kebab) // order-total
$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last) // gz
echo ' too many spaces '->squish() // too many spaces
$words = 'Hello, world!'->words() // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)->before()와 ->after()는 첫 번째 구분자에서 자르며, last를 주면 마지막 구분자에서 자르고, 구분자가 없으면 전체 텍스트를 돌려줍니다. ->wrap(width: 60)는 텍스트를 단어 사이에서 나누어 @terminal_width() 같은 너비에 맞춥니다. ->is_numeric()는 '42'나 '-3.5' 같은 텍스트에 대해 참입니다.
->contains(), ->starts_with(), ->ends_with(), ->index_of() (마지막 일치는 last와 함께) 및 ->replace()은 대소문자를 정확히 구분해서 일치시킵니다. 대소문자를 구분하지 않고 일치시키려면 ignore_case을 전달하세요:
<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true웹훅을 확인하려면 ->hmac(key)로 서명을 계산해요(기본값은 SHA-256이며, sha1 또는 sha512도 사용할 수 있어요). 그런 다음 두 값이 얼마나 일치하든 항상 같은 시간이 걸리는 @secure_equals()로 비교해요:
<let name="body" value="'{"id": 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true -->$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true->md5(), ->sha1(), ->sha256() 및 ->sha512()는 해시를 16진수로 반환합니다. @escape_regex(text)는 사용자가 입력한 내용을 이스케이프 처리하므로, 그 값으로 만든 패턴은 해당 텍스트와만 일치합니다.
리스트와 맵
목록은 ->difference(other), ->intersect(other), ->union(other)로 집합처럼 비교합니다. 각 함수는 첫 번째 목록의 순서를 유지하고, 모든 항목을 한 번씩만 반환하며, ==로 항목을 일치시키거나 by:가 각 항목에 대해 반환하는 값으로 일치시킵니다:
<let name="left" value="[1, 2, 3, 4]->difference([2, 4])" /> <!-- [1, 3] -->
<let name="both" value="['tea', 'milk']->union(['milk', 'sugar'])" /> <!-- ['tea', 'milk', 'sugar'] -->
<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<let name="kept" value="$people->intersect([{ id: 2 }], by: fn(p) => $p.id)" /> <!-- [{ id: 2, name: 'Bo' }] -->$left = [1, 2, 3, 4]->difference([2, 4]) // [1, 3]
$both = ['tea', 'milk']->union(['milk', 'sugar']) // ['tea', 'milk', 'sugar']
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
$kept = $people->intersect([{ id: 2 }], by: fn(p) => $p.id) // [{ id: 2, name: 'Bo' }]->count_by(fn)는 각 키의 항목 수를 셉니다. ->take_while(fn)와 ->skip_while(fn)는 조건에 맞지 않는 첫 항목에서 멈춥니다. ->window(size, step?)는 겹치는 구간을 반환하고, ->replace_at(index, item)는 한 항목만 바뀐 복사본을 반환합니다:
<let name="counts" value="['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first())" /> <!-- { a: 2, b: 1 } -->
<let name="pairs" value="['mon', 'tue', 'wed', 'thu']->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] -->
<let name="fixed" value="['tea', 'tae', 'milk']->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] -->$counts = ['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first()) // { a: 2, b: 1 }
$pairs = ['mon', 'tue', 'wed', 'thu']->window(2) // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']]
$fixed = ['tea', 'tae', 'milk']->replace_at(1, 'juice') // ['tea', 'juice', 'milk']가장 많이 나오는 것과 가장 적게 나오는 것: common
->common(count?, least, by?)는 각 항목이 몇 번 나오는지 세고, 그 순서대로 항목을 한 번씩만 반환합니다. least를 쓰지 않으면 가장 많이 나온 항목이 먼저 오고, least를 쓰면 가장 적게 나온 항목이 먼저 옵니다. count는 앞에서부터 그 개수만큼만 남기며, 생략하면 서로 다른 모든 항목을 얻습니다. 같은 횟수로 나온 항목은 목록에서 처음 등장한 순서를 유지하고, 각 항목은 원래 모습 그대로 반환되므로 숫자는 숫자로 남습니다:
<let name="basket" value="['apple', 'pear', 'apple', 'fig', 'fig', 'apple']" />
<!-- apple occurs 3 times, fig 2 times, pear once. -->
<echo value="$basket->common()" /> <!-- ['apple', 'fig', 'pear'] because that is most to least -->
<echo value="$basket->common(1)" /> <!-- ['apple'] because it is the 1st most common -->
<echo value="$basket->common(2)" /> <!-- ['apple', 'fig'] because those are the top 2 -->
<echo value="$basket->common(1, least)" /> <!-- ['pear'] because it is the 1st least common -->
<echo value="$basket->common(least)" /> <!-- ['pear', 'fig', 'apple'] because that is least to most -->$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig 2 times, pear once.
echo $basket->common() // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1) // ['apple'] because it is the 1st most common
echo $basket->common(2) // ['apple', 'fig'] because those are the top 2
echo $basket->common(1, least) // ['pear'] because it is the 1st least common
echo $basket->common(least) // ['pear', 'fig', 'apple'] because that is least to mostby:는 무엇을 같은 항목으로 볼지 결정합니다. 여기서 'Tea'와 'tea'는 둘 다 'tea'로 변환되므로 함께 세어지며, 먼저 나온 쪽이 반환됩니다:
<let name="drinks" value="['Tea', 'milk', 'tea']" />
<echo value="$drinks->common(1, by: fn(drink) => $drink->lower())" /> <!-- ['Tea'] because 'Tea' and 'tea' count as one, twice -->$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one, twice가장 많이 나온 숫자 세 개를 곱하려면 ->common(3)로 그 숫자들을 가져오고 ->product()로 곱하세요:
<let name="readings" value="[12, 7, 12, 9, 7, 12, 3]" />
<let name="top" value="$readings->common(3)" /> <!-- [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3 -->
<echo value="$top->product()" /> <!-- 756 because 12 * 7 * 9 is 756 -->$readings = [12, 7, 12, 9, 7, 12, 3]
$top = $readings->common(3) // [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3
echo $top->product() // 756 because 12 * 7 * 9 is 756맵에도 목록과 같은 콜백이 있으며, 콜백은 값을 먼저, 키를 나중에 받습니다: ->filter(), ->reject(), ->any(), ->all(), ->find()({ key, value }를 반환), ->reduce(), ->sort(by:) 및 ->map(). ->map_keys(fn)는 각 키의 이름을 바꾸며, 키를 먼저, 값을 나중에 받습니다:
<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<let name="empty" value="$stock->reject(fn(n) => $n > 0)" /> <!-- { pears: 0 } -->
<let name="order" value="$stock->sort(by: fn(n) => $n, order: desc)->keys()" /> <!-- ['apples', 'plums', 'pears'] -->
<let name="renamed" value="{ first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel))" /> <!-- { firstName: 'Ada' } -->$stock = { apples: 3, pears: 0, plums: 2 }
$empty = $stock->reject(fn(n) => $n > 0) // { pears: 0 }
$order = $stock->sort(by: fn(n) => $n, order: desc)->keys() // ['apples', 'plums', 'pears']
$renamed = { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) // { firstName: 'Ada' }집합(Set)
집합은 각 항목이 한 번씩만 나타나는 항목들의 묶음입니다. 이미 있는 항목을 추가하면 아무 일도 일어나지 않고, 항목이 집합에 있는지 확인하는 것은 집합이 아무리 커져도 빠르게 처리됩니다. 집합은 목록처럼 작성한 뒤 as set로 집합으로 만들거나, 변수나 필드를 set로 선언해서 만듭니다:
<let name="line" value="'rr?gb?r'" />
<let name="colours" value="$line->chars() as set" /> <!-- ['r', '?', 'g', 'b'] because each character goes in once -->
<echo value="($colours - ['?'])->count()" /> <!-- 3 because r, g and b are left once ? is taken away -->$line = 'rr?gb?r'
$colours = $line->chars() as set // ['r', '?', 'g', 'b'] because each character goes in once
echo ($colours - ['?'])->count() // 3 because r, g and b are left once ? is taken away집합은 이미 본 것을 기억할 때 가장 유용합니다. $seen: set = []은 빈 집합을 만들고, +=는 항목을 추가하며, in는 항목이 있는지 확인합니다. 두 작업 모두 집합이 커져도 빠르게 동작합니다:
<let name="seen" type="set" value="[]" />
<for each="place" in="['home', 'shop', 'home', 'park']">
<if $place in $seen>
<echo>back at { $place }</echo> <!-- back at home, once, because home was seen before -->
</if>
<set name="seen" op="+=" value="$place" />
</for>$seen: set = []
for place in ['home', 'shop', 'home', 'park'] {
if $place in $seen {
echo "back at { $place }" // back at home, once, because home was seen before
}
$seen += $place
}+는 두 집합을 합치고, -는 항목을 제거하며, ->intersect()는 두 집합에 모두 있는 항목만 남깁니다. 오른쪽 피연산자는 일반 목록일 수도 있습니다. set(of: string)는 한 가지 타입의 집합이며, 타입이 지정된 목록과 마찬가지로 항목이 들어올 때마다 해당 타입으로 변환됩니다. $set as list는 항목들을 목록으로 반환합니다. 집합의 모든 메서드와 예시는 Sets에서 확인할 수 있습니다.
<type name="Post">
<field name="title" type="string" />
<field name="tags" type="set(of: string)" default="[]" />
</type>
<let name="post" value="Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })" />
<echo value="$post.tags" /> <!-- ['news', 'tech'] because the second 'news' is already in the set -->
<echo value="$post.tags->overlaps(['tech'])" /> <!-- true -->
<echo value="$post.tags->is_subset(of: ['news', 'tech', 'sport'])" /> <!-- true because both tags are in the list -->type Post {
title: string
tags: set(of: string) = []
}
$post = Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })
echo $post.tags // ['news', 'tech'] because the second 'news' is already in the set
echo $post.tags->overlaps(['tech']) // true
echo $post.tags->is_subset(of: ['news', 'tech', 'sport']) // true because both tags are in the list형식 간 변환: convert
데이터는 형식 사이를 끊임없이 오갑니다. API는 JSON으로 응답하고, 설정 파일은 YAML이며, 스프레드시트는 CSV로 저장됩니다. 모든 값은 이 작업을 위한 메서드 하나, ->convert()를 가지며, 이는 문장처럼 읽힙니다: from 이 형식에서, to 저 형식으로 변환하라.
from:는 특정 형식으로 작성된 텍스트를 읽어 그 안의 값을 반환합니다. to:는 값을 특정 형식으로 씁니다. 두 가지를 함께 전달하면 한 형식을 곧바로 다른 형식으로 바꿀 수 있습니다.
| 형식 | from:로 읽기 |
to:로 쓰기 |
|---|---|---|
json |
맵, 목록, 텍스트, 숫자 | json 텍스트 |
yaml |
맵, 목록, 텍스트, 숫자 | yaml 텍스트 |
csv |
행의 목록 | csv 텍스트 |
markdown, latex |
문서 | KScript.Document 사용 |
html |
KScript.Markdown을 사용한 Markdown에서, KScript.Document를 사용한 문서에서 |
텍스트 읽기: from
from:는 텍스트를 받습니다. 텍스트 블록(예: ```yaml 또는 ```csv 블록), json 또는 csv 값, 또는 HTTP 응답(그 본문)도 받을 수 있습니다:
<let name="order" value="'{"fruit": "apple", "count": 3}'->convert(from: json)" />
<echo value="$order.count" /> <!-- 3 because the json text is now a map with a count key -->
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml).size" /> <!-- 12 because the yaml is read into a map -->$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count // 3 because the json text is now a map with a count key
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size // 12 because the yaml is read into a mapCSV는 기본적으로 헤더 줄을 가지며, 이 줄이 각 행의 키 이름을 정합니다. 모든 줄이 데이터일 때는 not header를 쓰세요. 그러면 각 행은 셀들의 목록이 됩니다:
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<echo value="$prices->convert(from: csv)[0].fruit" /> <!-- 'apple' because the header line names the fruit column -->
<echo value="$prices->convert(from: csv, not header)[0]" /> <!-- ['fruit', 'price'] because without a header the first line is a row too -->$prices = ```csv
fruit,price
apple,3
plum,5
```
echo $prices->convert(from: csv)[0].fruit // 'apple' because the header line names the fruit column
echo $prices->convert(from: csv, not header)[0] // ['fruit', 'price'] because without a header the first line is a row too타입으로 검사하기: as
as:는 읽은 값을 타입과 대조해 레코드로 변환합니다. 그래서 필드가 없거나 잘못되어도 나중에 뜻밖의 오류가 나는 대신, 그 값을 읽은 줄에서 바로 오류가 발생합니다. 레코드의 목록은 선언이 그렇게 쓰이듯 Fruit[]로 작성합니다:
<type name="Fruit">
<field name="fruit" type="string" />
<field name="price" type="int" />
</type>
<let name="prices">```csv
fruit,price
apple,3
plum,5
```</let>
<let name="fruits" value="$prices->convert(from: csv, as: Fruit[])" />
<echo value="$fruits[0].price + 1" /> <!-- 4 because as: Fruit[] turned the '3' cell into the int 3 -->type Fruit {
fruit: string
price: int
}
$prices = ```csv
fruit,price
apple,3
plum,5
```
$fruits = $prices->convert(from: csv, as: Fruit[])
echo $fruits[0].price + 1 // 4 because as: Fruit[] turned the '3' cell into the int 3형식으로 쓰기: to
to:는 모든 값을 씁니다. 맵과 목록은 JSON이나 YAML로, 행의 목록은 CSV로 씁니다. indented는 JSON을 여러 줄에 걸쳐 펼치고, headers:는 CSV 열을 골라 순서를 정합니다:
<let name="basket" value="[{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]" />
<echo value="$basket->convert(to: json)" /> <!-- [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line -->
<echo value="$basket->convert(to: json, indented)" /> <!-- the same json, one key a line, for people to read -->
<echo value="$basket->convert(to: csv, headers: ['count'])" /> <!-- "count", then "3" and "5" because only the count column is asked for -->$basket = [{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]
echo $basket->convert(to: json) // [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line
echo $basket->convert(to: json, indented) // the same json, one key a line, for people to read
echo $basket->convert(to: csv, headers: ['count']) // "count", then "3" and "5" because only the count column is asked for한 번에 둘 다
from:과 to:를 함께 주면, 중간에 값을 직접 다루지 않고도 한 형식을 다른 형식으로 바꿀 수 있습니다:
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml, to: json)" /> <!-- {"theme":"dark","size":12} because the yaml is read, then written as json -->$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml, to: json) // {"theme":"dark","size":12} because the yaml is read, then written as json축약형: from과 to
읽기만 하거나 쓰기만 할 때는 ->from(type: json)와 ->to(type: csv)로 같은 일을 더 짧게 표현할 수 있습니다. 두 메서드는 ->convert()와 같은 옵션을 받습니다:
<let name="order" value="'{"fruit": "apple"}'->from(type: json)" />
<echo value="$order.fruit" /> <!-- 'apple' because ->from(type: json) is ->convert(from: json) -->
<echo value="[{ fruit: 'plum' }]->to(type: json)" /> <!-- [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json) -->$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)->convert()이 형식을 바꾸는 유일한 방법이므로, 형식마다 하나씩 있던 예전 방식의 표기(->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), 그리고 문서의 ->html(), ->latex(), ->markdown())는 오류가 되며, 대신 작성해야 할 ->convert()를 보여 주고 편집기에서 수정 방법을 제시합니다.
구조화된 텍스트 읽기
데이터는 종종 텍스트로 들어옵니다. 한 줄에 레코드 하나씩이거나, 빈 줄로 구분된 줄 묶음이거나, 문자로 그린 그림일 수도 있습니다. 이 메서드들은 그런 텍스트를 다루기 쉬운 목록으로 바꿔 줍니다.
줄과 블록
->lines()는 한 줄당 텍스트 하나를 반환합니다. ->blocks()는 대신 빈 줄을 기준으로 텍스트를 나누므로, 각 블록은 줄들의 묶음이 됩니다. 한 번의 줄바꿈은 블록 안에 남고, 빈 줄만 새 블록을 시작합니다:
<let name="pantry">```text
tea
milk
flour
sugar
eggs
```</let>
<let name="shelves" value="$pantry->blocks()" />
<!-- ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block -->
<let name="counts" value="$shelves->map(.lines()->count())" />
<!-- [2, 3] because the first block has 2 lines and the second has 3 -->$pantry = ```text
tea
milk
flour
sugar
eggs
```
$shelves = $pantry->blocks()
// ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block
$counts = $shelves->map(.lines()->count())
// [2, 3] because the first block has 2 lines and the second has 3함수가 들어갈 자리에 쓰인 .lines()는 fn(block) => $block->lines()를 줄여 쓴 것입니다. 즉 각 항목에 대해 메서드를 호출하며, 이는 .name가 각 항목의 필드를 읽는 것과 같습니다. ->filter(.is_empty())나 ->sort(by: .age)처럼 함수가 들어가는 어느 곳에서든 동작합니다:
목록 나누기: split
이미 목록이 있을 때 ->split(separator)는 구분 항목이 나타나는 곳마다 목록을 잘라 여러 목록으로 만들며, 구분 항목은 버립니다. 일치시킬 값을 ==로 주거나, 구분 항목에 대해 참인 검사 함수를 줄 수 있습니다:
<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because a separator at the end leaves an empty list after it -->$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because a separator at the end leaves an empty list after it텍스트에 쓰면 ->split()는 텍스트를 자르고, 목록에 쓰면 ->split()는 목록을 자릅니다.
텍스트 속 숫자: numbers
->numbers()는 텍스트에 적힌 모든 숫자를 순서대로 반환하므로 그것을 위한 패턴을 따로 만들 필요가 없습니다. 마이너스 기호는 바로 앞에 아무것도 붙어 있지 않은 숫자 바로 앞에 있을 때 부호로 취급됩니다(예: x=-3). 두 숫자 사이에 있는 경우(예: 1-3)에는 대시로 취급되어 1와 3를 얻습니다:
<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->echo 'move 3 boxes from -1 to 12'->numbers() // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers() // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers() // [2.5, 4]문자로 그린 그림: grid
->grid()는 문자 줄들을 한 글자짜리 문자들의 행으로 바꾸므로, $grid[row][column]는 문자 하나입니다. 0번 행은 맨 위 줄이고 0번 열은 첫 글자입니다:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is '#.#' and column 1 is its second character -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
// [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1] // '.' because row 0 is '#.#' and column 1 is its second character
echo $plot[1][2] // '#' because row 1 is '..#' and column 2 is its last character행과 열 따라가기: cells
->cells()는 표를 읽듯이 그리드를 읽습니다. 단독으로 쓰거나 rows와 함께 쓰면 모든 행을 반환하고, columns와 함께 쓰면 위에서 아래로 모든 열을 반환합니다. 이렇게 두 방향 모두로 그리드를 순회할 수 있습니다:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<for each="row" in="$plot->cells(rows)">
<echo value="$row->join('')" />
</for>
<!-- '#.#' then '..#' because each row is one line of the picture -->
<for each="column" in="$plot->cells(columns)">
<echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because each column reads one character from every line, top to bottom -->
<echo value="$plot->cells(columns)->map(fn(column) => $column->count_of('#'))" />
<!-- [1, 0, 2] because only the last column has a # in both rows -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
for row in $plot->cells(rows) {
echo $row->join('')
}
// '#.#' then '..#' because each row is one line of the picture
for column in $plot->cells(columns) {
echo $column->join('')
}
// '#.' then '..' then '##' because each column reads one character from every line, top to bottom
echo $plot->cells(columns)->map(fn(column) => $column->count_of('#'))
// [1, 0, 2] because only the last column has a # in both rowsrow:는 한 행을, column:는 한 열을 고르며, 둘 다 0부터 셉니다. -1는 마지막 항목입니다. 둘을 함께 주면 두 위치가 만나는 셀 하나를 얻습니다:
<let name="garden">```text
#.#
..#
```</let>
<let name="plot" value="$garden->grid()" />
<echo value="$plot->cells(row: 0)" /> <!-- ['#', '.', '#'] because row 0 is the top line -->
<echo value="$plot->cells(column: -1)" /> <!-- ['#', '#'] because -1 is the last column, and both lines end in # -->
<echo value="$plot->cells(row: 1, column: 0)" /> <!-- '.' because row 1 is '..#' and column 0 is its first character -->$garden = ```text
#.#
..#
```
$plot = $garden->grid()
echo $plot->cells(row: 0) // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1) // ['#', '#'] because -1 is the last column, and both lines end in #
echo $plot->cells(row: 1, column: 0) // '.' because row 1 is '..#' and column 0 is its first character울퉁불퉁한 맵처럼 줄의 길이가 서로 다를 수 있습니다. 그러면 열은 그 열에 닿지 못할 만큼 짧은 행을 건너뛰며, 빈 칸을 채우기 위해 값을 만들어 넣지 않습니다:
<let name="steps">```text
#.#
#
```</let>
<echo value="$steps->grid()->cells(columns)" />
<!-- [['#', '#'], ['.'], ['#']] because the second line only reaches column 0 -->$steps = ```text
#.#
#
```
echo $steps->grid()->cells(columns)
// [['#', '#'], ['.'], ['#']] because the second line only reaches column 0->cells()는 그리드만이 아니라 모든 목록의 목록에서 동작합니다. [[1, 2], [3, 4]]->cells(columns)는 [[1, 3], [2, 4]]이며, 이는 행을 열로 바꿉니다.
그리드에서 항목 찾기: positions_of
->positions_of(item)는 그리드에서 항목이 있는 모든 위치를 .row와 .column를 가진 점들로 반환하며, 행 순서대로, 왼쪽에서 오른쪽으로 나열합니다. 함수를 주면, 셀에 대해 그 함수가 참인 위치들을 반환합니다:
<let name="garden">```text
#.#
..#
```</let>
<let name="trees" value="$garden->grid()->positions_of('#')" />
<!-- [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first -->
<echo value="$trees->contains({ row: 1, column: 2 })" /> <!-- true because there is a # at row 1, column 2 -->
<echo value="$trees->contains({ row: 1, column: 0 })" /> <!-- false because row 1 starts with a . -->$garden = ```text
#.#
..#
```
$trees = $garden->grid()->positions_of('#')
// [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 }) // true because there is a # at row 1, column 2
echo $trees->contains({ row: 1, column: 0 }) // false because row 1 starts with a .점은 ->combinations(2)와 함께 잘 동작합니다. 이는 모든 쌍을 한 번씩, 앞쪽 점이 먼저 오도록 반환합니다. 매개변수가 두 개인 함수는 쌍의 두 점을 하나씩 받습니다. 이 예시는 네 모서리가 모두 나무인 정사각형의 개수를 셉니다. 모서리 사이에 다른 나무가 있어도 상관없습니다:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})" />
<!-- 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
// only two trees on the same row can be a square's top corners
if $left.row != $right.row {
return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
$size = $right.column - $left.column
return $trees->contains({ row: $left.row + $size, column: $left.column })
and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them도형 찾기: shapes
->shapes()는 텍스트, 목록, 격자 또는 3D 목록에서 도형을 찾습니다. 내장 도형인 정사각형, 직사각형, 선, 원과, 직접 그린 도형인 마스크를 찾을 수 있습니다. 텍스트는 ->grid()가 읽는 방식대로, 한 행이 한 줄이고 한 셀이 한 글자입니다. 따라서 먼저 ->grid()를 호출할 필요가 없습니다. 격자의 셀에는 무엇이든 들어갈 수 있으므로, 내장 도형의 경우 of:는 어떤 셀이 도형을 이루는지 지정합니다. 예를 들어 '#' 같은 값이나 /[#@]/ 같은 정규식으로 지정합니다. 각 일치는 한 번만 { kind, points }로 반환되며, 각 점은 하나의 셀 { row, column, value }입니다. 도형의 점 사이에는 다른 셀이 있을 수 있습니다:
<let name="field">```text
#.##.
.....
.#...
##.##
```</let>
<echo value="$field->shapes(square, of: '#')->count()" />
<!-- 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them -->$field = ```text
#.##.
.....
.#...
##.##
```
echo $field->shapes(square, of: '#')->count()
// 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of themrotated를 쓰지 않으면 도형은 수평을 유지합니다. 정사각형과 직사각형의 변은 수평이고, 선은 가로 또는 세로로 뻗습니다. rotated를 쓰면 도형이 기울어질 수 있어, 정사각형이 마름모가 되거나 선이 대각선으로 뻗을 수 있습니다:
<let name="kite">```text
..#..
.#.#.
..#..
```</let>
<echo value="$kite->shapes(square, of: '#')->count()" /> <!-- 0 because no four #s make a square with level sides -->
<echo value="$kite->shapes(square, of: '#', rotated)->count()" /> <!-- 1 because the four #s make a diamond, a square on its corner -->$kite = ```text
..#..
.#.#.
..#..
```
echo $kite->shapes(square, of: '#')->count() // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count() // 1 because the four #s make a diamond, a square on its corner여러 도형을 지정하면 모두 찾습니다. 한 셀이 둘 이상의 도형에 맞아도 일치는 한 번만 반환됩니다. 예를 들어 정사각형은 직사각형이기도 하므로 정사각형으로 반환되며, .kind가 그 도형이 무엇인지 알려 줍니다:
<let name="plot">```text
@@@.
@..@
@@@@
```</let>
<echo value="$plot->shapes(rectangle, of: '@')->count()" /> <!-- 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2 -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" />
<!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well -->
<echo value="$plot->shapes(line, of: '@', size: 4)->count()" /> <!-- 1 because only the bottom row has 4 @s in a row -->
<echo value="$plot->shapes(line, of: '@', size: 3, rotated)->count()" /> <!-- 4 because rotated lets lines run diagonally too -->$plot = ```text
@@@.
@..@
@@@@
```
echo $plot->shapes(rectangle, of: '@')->count() // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well
echo $plot->shapes(line, of: '@', size: 4)->count() // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count() // 4 because rotated lets lines run diagonally too선에는 점이 몇 개인지 알려 주는 size:가 필요합니다. 원에는 radius:가 필요하고, distance:는 얼마나 떨어져 있어야 먼 것인지 정합니다. straight(직선 거리, 기본값), steps(가로와 세로만 계산하여 마름모를 그림) 또는 moves(대각선도 한 칸으로 계산하여 정사각형 고리를 그림):
<let name="pond">```text
.~.
~.~
.~.
```</let>
<echo value="$pond->shapes(circle, of: '~', radius: 1)->count()" /> <!-- 1 because the four ~s are each 1 away from the middle -->
<echo value="$pond->shapes(circle, of: '~', radius: 1, distance: moves)->count()" /> <!-- 0 because with moves the corners are 1 away too, and they aren't ~ -->$pond = ```text
.~.
~.~
.~.
```
echo $pond->shapes(circle, of: '~', radius: 1)->count() // 1 because the four ~s are each 1 away from the middle
echo $pond->shapes(circle, of: '~', radius: 1, distance: moves)->count() // 0 because with moves the corners are 1 away too, and they aren't ~->shapes()는 ->positions_of()가 주는 것처럼 점의 목록에도 작동합니다. 또는 csv에서 읽은 행에도 작동합니다. 이 경우 모든 점이 포함되므로 of:가 필요 없습니다: $trees->shapes(square, rotated).
직접 만드는 도형: 마스크
마스크는 직접 그리는 도형입니다. 내장 도형은 점이 어디 있는지만 알지만, 마스크는 간격을 포함하여 모든 셀이 정확히 무엇을 담아야 하는지 말해 줍니다. extends Mask하는 타입으로 선언하고, layout에서 그립니다. 이는 도형을 그림으로 보여 주는 텍스트 블록으로, 한 글자가 한 셀입니다. (길이가 정해지지 않은 행 도형에는 정규식을 쓸 수도 있습니다: 정규식 레이아웃). 각 글자는 같은 글자를 담은 셀과 일치합니다. 모든 줄이 공유하는 들여쓰기는 그림의 일부가 아니므로, 주변 코드와 함께 들여쓰면 됩니다.
#로 이루어진 속이 꽉 찬 2x2 블록을 찾으려면, 그것을 그리고 이름으로 마스크를 ->shapes()에 넘깁니다:
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<let name="roof">```text
###.
###.
...#
```</let>
<let name="blocks" value="$roof->shapes(Block)" /> <!-- the matches, top left first -->
<echo value="$blocks->count()" /> <!-- 2 because the block fits at columns 0-1 and again at columns 1-2 -->
<echo value="$blocks->first().kind" /> <!-- 'Block' because a mask's match is named after its type -->
<echo value="$blocks->first().points->map(.column)" /> <!-- [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1 -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
$roof = ```text
###.
###.
...#
```
$blocks = $roof->shapes(Block) // the matches, top left first
echo $blocks->count() // 2 because the block fits at columns 0-1 and again at columns 1-2
echo $blocks->first().kind // 'Block' because a mask's match is named after its type
echo $blocks->first().points->map(.column) // [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1symbols는 자기 자신이 아닌 다른 의미를 가진 글자에만 씁니다. 글자를 그것이 일치하는 대상에 대응시킵니다. 값(t: 'taken')은 그 값을 담은 셀과 일치하고, 정규식(/[#@]/)은 텍스트가 맞는 셀과, fn(cell)는 참을 돌려주는 셀과 일치합니다. same는 모두 같은 값을 담아야 하는 셀(아래)에, any는 도형의 일부가 아닌 셀에 대응합니다. any 셀에는 무엇이든 들어갈 수 있고, 입력의 가장자리 밖으로 넘어갈 수도 있으며, 일치의 점에서는 제외됩니다. 3x3 정사각형의 네 모서리에 나무가 있고 그 사이에는 무엇이든 있어도 되는 나무 네 그루를 찾으려면:
<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
<field name="layout" default="```text
#.#
...
#.#
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="orchard">```text
#.#.#
.#...
#.#.#
```</let>
<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
layout: ```text
#.#
...
#.#
```
symbols: { '.': any }
}
$orchard = ```text
#.#.#
.#...
#.#.#
```
echo $orchard->shapes(Corners)->count() // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middlesymbols는 셀이 한 글자가 아닐 때 제 역할을 합니다. 좌석 한 줄은 단어의 목록이고, 값의 목록은 한 행이므로, 레이아웃에는 단어마다 글자 하나가 필요합니다:
<type name="QuietPair" description="Two free seats side by side, with a taken seat on each side." extends="Mask">
<field name="layout" default="```text
tfft
```" />
<field name="symbols" default="{ t: 'taken', f: 'free' }" />
</type>
<let name="row" value="['free', 'taken', 'free', 'free', 'taken', 'taken']" />
<echo value="$row->shapes(QuietPair)->count()" /> <!-- 1 because only seats 1 to 4 read taken, free, free, taken -->/// Two free seats side by side, with a taken seat on each side.
type QuietPair extends Mask {
layout: ```text
tfft
```
symbols: { t: 'taken', f: 'free' }
}
$row = ['free', 'taken', 'free', 'free', 'taken', 'taken']
echo $row->shapes(QuietPair)->count() // 1 because only seats 1 to 4 read taken, free, free, taken->shapes()는 마스크 하나 또는 그 목록을 받고, rotated는 입력이 허용하는 모든 방향으로 각각을 돌립니다. 행을 따라 앞뒤로 뒤집고, 격자에서는 4분의 1, 2분의 1, 4분의 3만큼 회전하며, 3D에서는 24가지 방향 모두를 사용합니다. 여러 마스크의 일치는 함께 반환되며 각각은 .kind로 이름이 붙습니다. 마스크와 내장 도형을 한 번의 호출에서 함께 찾을 수 있습니다:
<type name="Fork" description="Three trees in a V, with anything between them." extends="Mask">
<field name="layout" default="```text
t~t
~t~
```" />
<field name="symbols" default="{ t: /[#@]/, '~': any }" />
</type>
<type name="Gap" description="Two trees with a clearing between them." extends="Mask">
<field name="layout" default="```text
#.#
```" />
</type>
<let name="wood">```text
#.@
.#.
#.#
```</let>
<echo value="$wood->shapes(Fork)->count()" /> <!-- 1 because the V fits only with its point at the bottom -->
<echo value="$wood->shapes(Fork, rotated)->count()" /> <!-- 4 because turned a quarter, a half and three quarters, it fits once each way -->
<echo value="$wood->shapes([Fork, Gap], rotated)->map(.kind)" />
<!-- ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.# -->
<echo value="$wood->shapes(Fork)->first().points->map(.symbol)" />
<!-- ['t', 't', 't'] because ~ is any, so its cells aren't part of the match -->/// Three trees in a V, with anything between them.
type Fork extends Mask {
layout: ```text
t~t
~t~
```
symbols: { t: /[#@]/, '~': any }
}
/// Two trees with a clearing between them.
type Gap extends Mask {
layout: ```text
#.#
```
}
$wood = ```text
#.@
.#.
#.#
```
echo $wood->shapes(Fork)->count() // 1 because the V fits only with its point at the bottom
echo $wood->shapes(Fork, rotated)->count() // 4 because turned a quarter, a half and three quarters, it fits once each way
echo $wood->shapes([Fork, Gap], rotated)->map(.kind)
// ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.#
echo $wood->shapes(Fork)->first().points->map(.symbol)
// ['t', 't', 't'] because ~ is any, so its cells aren't part of the match마스크의 기호는 사용하는 곳에서 바꿀 수 있으며, 다른 필드와 마찬가지입니다. Fork(symbols: { t: fn(cell) => $cell != '.', '~': any })는 .를 제외한 모든 것과 같은 V입니다.
레이아웃에서 빈 줄은 다음 층을 시작하며, 마스크가 훑는 텍스트에서 빈 줄이 하는 것과 같습니다. 맨 위 층이 먼저입니다. 모든 층은 행 수가 같아야 하며, 3D에서 일치의 각 점에도 layer가 있습니다. 3D 목록($cube[layer][row][column])도 같은 방식으로 읽습니다:
<type name="Step" description="A step: one block on the top layer, with two under it on the layer below." extends="Mask">
<field name="layout" default="```text
#.
##
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="tower">```text
#..
...
##.
.#.
```</let>
<echo value="$tower->shapes(Step)->count()" /> <!-- 1 because the one block on the top layer has a block under it, and another beside that -->
<echo value="$tower->shapes(Step)->first().points->map(.layer)" /> <!-- [0, 1, 1] because one point is on the top layer and two are on the layer below -->/// A step: one block on the top layer, with two under it on the layer below.
type Step extends Mask {
layout: ```text
#.
##
```
symbols: { '.': any }
}
$tower = ```text
#..
...
##.
.#.
```
echo $tower->shapes(Step)->count() // 1 because the one block on the top layer has a block under it, and another beside that
echo $tower->shapes(Step)->first().points->map(.layer) // [0, 1, 1] because one point is on the top layer and two are on the layer below층이나 행이 입력보다 적은 마스크는 입력 전체를 미끄러지듯 훑습니다. 한 줄짜리 마스크는 격자의 모든 행에서 시도되고, 평면 마스크는 3D 텍스트나 3D 목록의 모든 층에서 시도됩니다. 입력보다 많은 층이나 행이 있는 마스크는 오류이며, 예를 들어 "Step has 2 layers, and this is one grid." 같이 그 사실을 알려 줍니다.
Mask는 매개변수나 필드에 쓸 수 있는 타입입니다. Mask를 확장하는 모든 타입을 받으며, 타입 자체(Block)나 그것으로 만든 타입(Block(symbols: ...))을 받습니다. Mask[]는 그것들의 목록을 받습니다:
<type name="Block" description="Four #s packed into a square." extends="Mask">
<field name="layout" default="```text
##
##
```" />
</type>
<fn name="count_in" params="input: string, shape: Mask" returns="int" value="$input->shapes($shape)->count()" />
<fn name="count_all" params="input: string, shapes: Mask[]" returns="int" value="$input->shapes($shapes)->count()" />
<let name="roof">```text
###.
###.
...#
```</let>
<echo value="@count_in($roof, Block)" /> <!-- 2 because Block fits twice in the roof -->
<echo value="@count_in($roof, Block(symbols: { '#': /[#.]/ }))" /> <!-- 6 because now a . counts as well, so every 2x2 window fits -->
<echo value="@count_all($roof, [Block, Block(symbols: { '#': '.' })])" /> <!-- 2 because no 2x2 of the roof is all .s, so only Block's 2 count -->/// Four #s packed into a square.
type Block extends Mask {
layout: ```text
##
##
```
}
fn count_in(input: string, shape: Mask): int => $input->shapes($shape)->count()
fn count_all(input: string, shapes: Mask[]): int => $input->shapes($shapes)->count()
$roof = ```text
###.
###.
...#
```
echo @count_in($roof, Block) // 2 because Block fits twice in the roof
echo @count_in($roof, Block(symbols: { '#': /[#.]/ })) // 6 because now a . counts as well, so every 2x2 window fits
echo @count_all($roof, [Block, Block(symbols: { '#': '.' })]) // 2 because no 2x2 of the roof is all .s, so only Block's 2 count서로 같아야 하는 셀: same
지금까지의 모든 기호는 셀을 고정된 무언가와 비교합니다. same는 셀끼리 비교합니다. 그 글자로 그려진 모든 셀은 값이 무엇이든 하나의 값을 담아야 하며, 서로 다른 same 글자는 서로 다른 값을 담아야 합니다. same(...)는 그 값이 무엇일 수 있는지 좁히며, 값, 정규식 또는 fn(cell)로 지정합니다. oxxo처럼 앞뒤로 읽어도 같은 단어를 찾으려면:
<type name="Mirror" description="Two letters, then the same two backwards, like 'abba'." extends="Mask">
<field name="layout" default="```text
xyyx
```" />
<field name="symbols" default="{ x: same(/[a-z]/), y: same(/[a-z]/) }" />
</type>
<echo value="'ioxxoj'->shapes(Mirror)->count()" /> <!-- 1 because only 'oxxo' reads the same letters out and back -->
<echo value="'ioxxoj'->shapes(Mirror)->first().points->map(.value)" /> <!-- ['o', 'x', 'x', 'o'] because x is o and y is x there -->
<echo value="'aaaa'->shapes(Mirror)->count()" /> <!-- 0 because x and y are different characters, so they hold different letters -->/// Two letters, then the same two backwards, like 'abba'.
type Mirror extends Mask {
layout: ```text
xyyx
```
symbols: { x: same(/[a-z]/), y: same(/[a-z]/) }
}
echo 'ioxxoj'->shapes(Mirror)->count() // 1 because only 'oxxo' reads the same letters out and back
echo 'ioxxoj'->shapes(Mirror)->first().points->map(.value) // ['o', 'x', 'x', 'o'] because x is o and y is x there
echo 'aaaa'->shapes(Mirror)->count() // 0 because x and y are different characters, so they hold different letters어떤 길이든 되는 도형: 정규식 레이아웃
그림은 크기가 고정되어 있습니다. 대신 레이아웃을 정규식으로 쓸 수 있는데, 이는 각 행을 따라 셀을 하나씩 차례로 읽고, 필요한 만큼 일치시킵니다. 각 셀은 그 텍스트로 읽히며, 일치는 셀 사이에서 시작하고 끝나야 합니다. 정규식 레이아웃에는 symbols가 없습니다. 부분에 (?<name>...)로 이름을 붙이면, 각 점의 symbol는 그 점이 속한 부분의 이름이 됩니다:
<type name="PartNumber" description="A part number: digits side by side, each one named a digit." extends="Mask">
<field name="layout" default="/(?<digit>\d)+/" />
</type>
<let name="schematic">```text
467..114
...*....
..35.633
```</let>
<echo value="$schematic->shapes(PartNumber)->count()" /> <!-- 4 because 467, 114, 35 and 633 are each a run of digits -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.column)" /> <!-- [0, 1, 2] because 467 fills the first three columns of row 0 -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.symbol)" /> <!-- ['digit', 'digit', 'digit'] because each cell fell in the digit part -->/// A part number: digits side by side, each one named a digit.
type PartNumber extends Mask {
layout: /(?<digit>\d)+/
}
$schematic = ```text
467..114
...*....
..35.633
```
echo $schematic->shapes(PartNumber)->count() // 4 because 467, 114, 35 and 633 are each a run of digits
echo $schematic->shapes(PartNumber)->first().points->map(.column) // [0, 1, 2] because 467 fills the first three columns of row 0
echo $schematic->shapes(PartNumber)->first().points->map(.symbol) // ['digit', 'digit', 'digit'] because each cell fell in the digit partrotated를 쓰면 정규식 레이아웃은 각 행을 뒤에서 앞으로도 읽고, 격자에서는 각 열을 위아래로도 읽습니다. 단어의 목록은 셀마다 단어 하나씩 읽히므로, /\d+/를 ['ab', '12', '34']에 적용하면 ['12', '34']를 찾습니다.
반복해서 찍기: repeated
repeated를 쓰면 마스크는 쿠키 틀과 같습니다. 왼쪽 위에서 시작해 입력 전체를 덮을 때까지 계속 찍히며, 오른쪽과 아래 가장자리의 복사본은 잘립니다. 모든 복사본이 첫 번째 복사본과 셀마다 같은 내용을 담으면 맞는 것입니다(any 셀은 자유롭습니다). 일치는 첫 번째 복사본이며, copies는 몇 번 찍혔는지 알려 줍니다:
<type name="Checker" description="One black and one white tile, and the same two swapped below." extends="Mask">
<field name="layout" default="```text
#.
.#
```" />
</type>
<let name="floor">```text
#.#.#
.#.#.
#.#.#
```</let>
<echo value="$floor->shapes(Checker, repeated)->count()" /> <!-- 1 because the whole floor is a checkerboard -->
<echo value="$floor->shapes(Checker, repeated)->first().copies" /> <!-- 6 because 2 rows of 3 stamps cover it, the last row and column cut off -->
<echo value="'#..'->shapes(Checker, repeated)->count()" /> <!-- 0 because the third cell should be # like the first -->/// One black and one white tile, and the same two swapped below.
type Checker extends Mask {
layout: ```text
#.
.#
```
}
$floor = ```text
#.#.#
.#.#.
#.#.#
```
echo $floor->shapes(Checker, repeated)->count() // 1 because the whole floor is a checkerboard
echo $floor->shapes(Checker, repeated)->first().copies // 6 because 2 rows of 3 stamps cover it, the last row and column cut off
echo '#..'->shapes(Checker, repeated)->count() // 0 because the third cell should be # like the first정규식 레이아웃은 고정된 크기가 없으므로 repeated를 쓰면 가장 짧은 틀부터 시도하여 맞는 가장 짧은 것을 줍니다. 행을 따라 찍힌 처음 size 셀이 행을 이루어야 하며, 정규식은 그 셀 전체와 맞아야 합니다. 행 하나만 읽으므로 한 번에 한 줄씩 주세요:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="printed" value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first()" />
<echo value="$printed.points->map(.value)->join('')" /> <!-- 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr -->
<echo value="$printed.copies" /> <!-- 4 because the fourth rgb is cut off after its r -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$printed = 'rgbrgbrgbr'->shapes(Instructions, repeated)->first()
echo $printed.points->map(.value)->join('') // 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr
echo $printed.copies // 4 because the fourth rgb is cut off after its r어떤 것과도 맞는 셀: blank
입력이 손상되었거나 알 수 없을 때가 있습니다. blank:는 어떤 것과도 맞는 셀을 지정하며, 값('?'), 정규식 또는 fn(cell)로 지정합니다. 빈 셀은 모든 기호와 맞고, same나 repeated에서는 비교되지 않으므로, 복사본들이 서로의 빈칸을 채웁니다. 점의 value는 다른 복사본이 값을 알고 있을 때 채워진 값입니다. blank:는 마스크가 아니라 호출에 씁니다. 모양이 아니라 입력을 설명하기 때문입니다:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="cutter" value="'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()" />
<echo value="$cutter.points->count()" /> <!-- 5 because no shorter cutter agrees with every colour that can be read -->
<echo value="$cutter.points->map(.value)->join('')" /> <!-- 'o?yv?' because the y comes from the second copy, and two cells are never read -->
<echo value="'???'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 1 because a barcode of blanks fits one instruction -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$cutter = 'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()
echo $cutter.points->count() // 5 because no shorter cutter agrees with every colour that can be read
echo $cutter.points->map(.value)->join('') // 'o?yv?' because the y comes from the second copy, and two cells are never read
echo '???'->shapes(Instructions, repeated, blank: '?')->first().points->count() // 1 because a barcode of blanks fits one instruction내장 도형도 blank:를 받으며, of:는 값이나 정규식뿐 아니라 fn(cell)도 받아서 세 가지 모두 셀을 같은 방식으로 읽습니다. $field->shapes(square, of: '#', blank: '?')는 ?를 #로 셉니다.
바코드의 행 목록에서 도형을 찾으려면, 줄마다 적용합니다:
<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="barcodes">```text
rgbrgbrgbr
?rv
??b?????
```</let>
<echo value="$barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())" />
<!-- 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b) -->/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$barcodes = ```text
rgbrgbrgbr
?rv
??b?????
```
echo $barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())
// 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b)마스크는 layout, symbols와 자체 메서드를 담으며, :로 씁니다. 편집기와 kscript check는 잘못 쓴 마스크를 보고하며, 대부분 수정 방법을 함께 알려 줍니다. 예를 들면 레이아웃이 없거나 비어 있는 경우, 레이아웃이 전부 any인 경우, 그림에 탭이 있는 경우, 층의 높이가 다른 경우, 기호가 한 글자보다 길거나 두 번 나열된 경우, null 대신 any를 쓴 경우, 따옴표 안의 'same'를 same 대신 쓴 경우, 정규식 레이아웃 옆의 symbols, layout = 대신 layout:를 쓴 경우, 내장 도형에서의 repeated, ->find_all()나 ->matches()(정규식을 받음)에 마스크를 준 경우, 그리고 like:는 ->shapes()가 더 이상 받지 않는다는 것입니다. 레이아웃이 쓰지 않는 기호는 경고(KS6026)이며, 글자를 자기 자신에 대응시키는 기호도 경고(KS6025)입니다. 모든 글자는 이미 자기 자신과 일치하기 때문입니다:
<type name="Block" extends="Mask">
<field name="layout" default="```text
##
```" />
<field name="symbols" default="{ '#': '#' }" /> <!-- the warning: '#' already matches '#'. -->
</type>type Block extends Mask {
layout: ```text
##
```
symbols: { '#': '#' } // the warning: '#' already matches '#'.
}편집기에서 마스크는 언어의 일부입니다. extends ‸는 Mask를 제안하며, Mask 타입 안에서 layout를 입력하면 텍스트 블록이 써집니다. 일단 블록이 있으면 symbols는 레이아웃의 글자와 any로 완성되어 나타납니다. symbols: { } 안에서는 아직 나열되지 않은 레이아웃의 글자를 완성 목록으로 제안하고, 키 뒤의 콜론 다음에는 any, same, same(/…/), 값, 정규식과 fn(cell)를 제안합니다. layout: 뒤에는 텍스트 블록과 정규식을 제안합니다. 서명 도우미는 마스크를 쓰는 동안 ->shapes(mask, rotated?, repeated?, blank?)를 보여 줍니다. 레이아웃의 글자에 마우스를 올리면 그것이 무엇과 맞는지, 그리고 레이아웃이 그것을 몇 번 쓰는지 알려 주며, 각 글자는 맞는 대상에 따라 색이 칠해집니다. 자기 자신이나 텍스트 같은 값은 한 색으로, 정규식은 정규식의 색으로, fn는 함수의 색으로, any는 주석처럼 흐리게 표시됩니다.
순서 다루기
곱하기: product
->product(fn?)는 항목들을 곱합니다. ->sum()가 항목들을 더하는 것과 같습니다. 함수가 주어지면 각 항목에 대해 함수가 준 값을 곱합니다. 정수는 크기와 관계없이 정확하게 유지됩니다:
<echo value="[2, 3, 4]->product()" /> <!-- 24 because 2 * 3 * 4 is 24 -->
<let name="boxes" value="[{ width: 2, height: 5 }, { width: 3, height: 1 }]" />
<echo value="$boxes->product(fn(box) => $box.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[942, 945, 571]->product()" /> <!-- 508298490 -->echo [2, 3, 4]->product() // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2, height: 5 }, { width: 3, height: 1 }]
echo $boxes->product(fn(box) => $box.width) // 6 because 2 * 3 is 6
echo [942, 945, 571]->product() // 508298490누적 합계: scan
->scan(fn(total, item), initial?)는 ->reduce()와 같이 작동하지만 중간의 모든 합계를 유지하므로, 결과가 어떻게 쌓이는지 볼 수 있습니다. initial가 없으면 첫 번째 항목이 첫 번째 합계가 됩니다:
<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" />
<!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" />
<!-- [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it -->$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount)
// [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20)
// [15, 13, 5, 4] because the budget starts at 20 and each amount comes off it모든 선택: combinations
->combinations(size)는 순서가 중요하지 않을 때 목록에서 size개 항목을 고르는 모든 방법을 제공해요. 각 조합은 목록 순서를 유지하며, 같은 조합에 같은 항목을 두 번 고르지 않아요.
목록 ['tea', 'milk', 'juice']에서 2개를 고르면 다음과 같아요. tea부터 시작해 그 뒤의 각 항목(milk, 그다음 juice)과 짝을 짓고, 그다음 milk부터 시작해 그 뒤의 각 항목(juice)과 짝을 지어요. juice 뒤에는 항목이 없으므로 더 없어요. ['milk', 'tea']는 ['tea', 'milk']와 같은 조합이므로 나오지 않아요:
<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->combinations(2)" />
<!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->
<echo value="$drinks->combinations(3)" />
<!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->
<echo value="$drinks->combinations(1)" />
<!-- [['tea'], ['milk'], ['juice']] -->$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2)
// [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3)
// [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(1)
// [['tea'], ['milk'], ['juice']]흔한 용도는 모든 짝을 확인하는 거예요. 예를 들어 합이 특정 금액이 되는 두 가격을 찾을 때 써요:
<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
// [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is고른 항목 수만큼 매개변수가 있는 함수는 항목을 하나씩 받으므로 $two[0]과 $two[1]를 직접 읽지 않고 이름으로 쓸 수 있어요. 어떤 크기에서도 동작해요. 3개를 고르면 fn(first, second, third)를 채워요. 매개변수가 하나뿐인 함수는 조합 전체를 받아요:
<let name="prices" value="[15, 40, 25, 60]" />
<echo value="$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)" />
<!-- 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is -->
<let name="sides" value="[3, 4, 5, 9]" />
<echo value="$sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)" />
<!-- 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25 -->
<echo value="$sides->combinations(3)->map(fn(three) => $three->sum())" />
<!-- [12, 16, 17, 18] because a function with one parameter gets each pick as a list -->$prices = [15, 40, 25, 60]
echo $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)
// 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is
$sides = [3, 4, 5, 9]
echo $sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)
// 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25
echo $sides->combinations(3)->map(fn(three) => $three->sum())
// [12, 16, 17, 18] because a function with one parameter gets each pick as a list고른 항목이 매개변수를 채우기 때문에 이런 함수는 인덱스를 함께 받지 않아요. 짝을 고르면 fn(first, second)은 그 짝의 두 항목이에요.
모든 순서: 순열
->permutations(size?)는 순서가 중요할 때 모든 배열을 제공하므로 ['tea', 'milk']와 ['milk', 'tea']가 모두 포함돼요. size가 없으면 각 배열은 모든 항목을 사용해요:
<echo value="['tea', 'milk', 'juice']->permutations()" />
<!--
6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
-->
<echo value="['tea', 'milk', 'juice']->permutations(2)->count()" />
<!-- 6 because 3 choices for first and 2 for second -->echo ['tea', 'milk', 'juice']->permutations()
// 6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
// because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
echo ['tea', 'milk', 'juice']->permutations(2)->count()
// 6 because 3 choices for first and 2 for second조합과 순열은 빠르게 늘어나요(항목 10개면 3,628,800가지 순서가 나와요). 그래서 목록이 100만 개를 넘으면 메모리가 부족해지기 전에 Limit 오류로 멈춰요.
방향 바꾸기: rotate
->rotate(by)는 모든 항목을 by칸씩 앞쪽으로 옮기고, 앞에서 밀려난 항목은 뒤에 붙여요. 음수 by는 반대 방향으로 돌려요:
<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1) // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1) // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front타입에 메서드 추가하기: extend
extend는 내장 타입이든 직접 만든 타입이든 거기에 나만의 메서드를 추가해요. 블록 안에서 각 fn가 메서드이고, $this는 메서드가 호출된 값이에요:
<extend type="date">
<fn name="api_date" description="The date as text for an API: 2026-11-21." value="$this->format('yyyy-MM-dd')" />
<fn name="is_payday" value="$this.day == 25" />
</extend>
<extend type="list">
<fn name="second" value="$this[1]" />
</extend>
<extend type="string">
<fn name="slug" value="$this->lower()->trim()->replace(' ', '-')" />
</extend>
<echo>{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }</echo>
<echo>{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }</echo>extend date {
/// The date as text for an API: 2026-11-21.
fn api_date() => $this->format('yyyy-MM-dd')
fn is_payday() => $this.day == 25
}
extend list {
fn second() => $this[1]
}
extend string {
fn slug() => $this->lower()->trim()->replace(' ', '-')
}
echo "{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }"
echo "{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }"string, number(또는 int와 float), bool, list, set, map, fn, date, email, password, handle, uuid, regex를 확장할 수 있고, file나 response 같은 패키지 값도 확장할 수 있어요. 직접 만든 type에도 쓸 수 있는데, 그 메서드에서는 $this(레코드)와 그 필드를 $this.name로 볼 수 있어요. 메서드도 모든 fn처럼 매개변수, 기본값, 이름 있는 인자를 받을 수 있어요.
타입이 이미 가진 이름과 같은 메서드는 추가할 수 없으므로 오타나 이름 충돌이 내장 메서드 동작을 바꾸지 않아요. 일부러 교체하려면 override를 쓰세요:
<extend type="date">
<fn name="to_string" override="yes" value="$this->format('d MMMM yyyy')" />
</extend>extend date {
override fn to_string() => $this->format('d MMMM yyyy')
}XML에서 extend은 <fn> 요소를 담은 <extend type="date">이고, override fn는 <fn override="true">예요.
확장이 적용되는 범위. 파일 안의 extend 블록은 그 파일과, 그 파일을 가져오는 모든 파일에 적용돼요. 프로젝트(kscript.json가 있는 폴더)에서는 extensions/ 폴더의 모든 파일이 가져오기 없이 프로젝트의 모든 스크립트, 테스트, 페이지에 적용돼요. 예를 들어 타입마다 파일을 하나씩 두는 식으로 자유롭게 나눌 수 있어요:
extensions/
date.kscript extend date { … }
list.kscript extend list { … }
text/
slug.kscript extend string { … }kscript make extension date --methods api_date,is_payday는 시작점으로 extensions/date.kscript를 작성해요. 다른 위치에 두려면 kscript.json에 폴더나 글로브를 나열하세요. 이렇게 하면 기본 폴더 "extensions": ["extensions", "shared/**/*.kscript"]는 대체돼요. 같은 타입의 같은 메서드를 추가하는 확장 파일 두 개는 오류이며, 오류 메시지에 두 파일 모두 표시돼요. 스크립트 자체의 extend(또는 가져오기)가 프로젝트의 것보다 우선해요.
편집기는 확장 메서드를 적용되는 곳에서만 자동 완성하고 검사해요. 파일이 선언하거나 가져오지 않고, 프로젝트를 통해서도 받지 않았다면 날짜에 대한 ->api_date()는 여전히 알 수 없는 메서드예요. 마우스를 올리면 메서드의 /// 문서와 어떤 파일이 추가했는지 보이고, 정의로 이동하면 그 파일이 열려요. @today()->api_date()