學習軌道
/
Factor
Factor
/
練習
/
日誌等級
日誌等級

日誌等級

學習練習

簡介

在 Factor 中,字串是一連串的字元。除了 splitting、ascii 等詞彙中專門處理字串的詞之外,sequences 詞彙中的大多數詞也能用於字串。

字串字面值

字串以雙引號撰寫。常見的跳脫序列都支援:\n、\t、\r、\\、\":

"hello, world" .                 ! => "hello, world"
"first\nsecond" print            ! prints two lines

長度與索引

因為字串是序列,sequences 詞彙中的length與nth可以直接用於字串。

length會回傳字元的數量:

"hello" length .    ! => 5

nth接受一個從 0 開始的索引和序列,並回傳該位置的元素。對字串而言,元素是一個字元,也就是一個碼位(整數),而不是長度為一的子字串:

0 "hello" nth .     ! => 104   (CHAR: h)
4 "hello" nth .     ! => 111   (CHAR: o)

從字元回到字串

要把單一碼位轉成單一字元的字串,可以使用 strings 詞彙中的1string ( char -- str )。CHAR:是字面碼位的剖析時期形式:

CHAR: A 1string .                ! => "A"
0 "hello" nth 1string .          ! => "h"

分割

splitting 詞彙能把字串切成片段。

split1會在分隔符號第一次出現的位置切開,並回傳前後兩半:

split1 ( seq subseq -- before after )
"foo: bar" ": " split1 .s
! => "foo"
! => "bar"

split會在分隔字元集合中任一個字元處切開,可能產生空片段:

"[ERROR]: Stack overflow" "[]" split .
! => { "" "ERROR" ": Stack overflow" }

harvest(位於 sequences)會捨棄空片段:

"[ERROR]: Stack overflow" "[]" split harvest .
! => { "ERROR" ": Stack overflow" }

取出某個片段

字串被分割成片段的陣列之後,first、second、third和fourth(位於 sequences)會回傳該位置的片段:

"apple,bee,carrot,duck" "," split first .    ! => "apple"
"apple,bee,carrot,duck" "," split second .   ! => "bee"
"apple,bee,carrot,duck" "," split third .    ! => "carrot"
"apple,bee,carrot,duck" "," split fourth .   ! => "duck"

當你想一次把前面幾個片段放到堆疊上時,first2和first3可以一步拆出其中兩個或三個:

"apple,bee,carrot,duck" "," split first2 .s
! => "apple"
! => "bee"

"apple,bee,carrot,duck" "," split first3 .s
! => "apple"
! => "bee"
! => "carrot"

用於字串本身時,first回傳的是第一個字元,也就是碼位,而不是子字串:

"hello" first .                         ! => 104   (CHAR: h)

修剪

[ blank? ] trim(來自 sequences,其中blank?來自 ascii 詞彙)會移除前後的空白:

"  Disk full \r\n" [ blank? ] trim .
! => "Disk full"

大小寫轉換

>lower和>upper(來自 ascii)會回傳大小寫改變後的新字串:

"WARNING" >lower .    ! => "warning"
"hello" >upper .      ! => "HELLO"

連接

sequences 詞彙中有兩個詞可以組裝字串:

surround會用前綴和後綴包住字串:

surround ( seq pre post -- new-seq )
"warning" "(" ")" surround .    ! => "(warning)"

glue會用分隔符號連接兩個字串:

glue ( s1 s2 sep -- s )
"Disk full" "(error)" " " glue .    ! => "Disk full (error)"

說明

在這道練習中,你會處理日誌行。

每行日誌都是格式化為 "[<LEVEL>]: <MESSAGE>" 的字串。

日誌層級有三種:INFO、WARNING 和 ERROR。

你有三個任務。每個任務會從堆疊取出一行日誌。

1. 從日誌行取得訊息

定義message,回傳日誌行裡的訊息。開頭和結尾的空白都應該移除。

"[ERROR]: Invalid operation" message .
! => "Invalid operation"

"[WARNING]:  Disk almost full\r\n" message .
! => "Disk almost full"

2. 從日誌行取得日誌層級

定義log-level,回傳日誌行的層級,並轉成小寫。

"[ERROR]: Invalid operation" log-level .
! => "error"

3. 重新格式化日誌行

定義reformat,把訊息放在最前面,並在後面用括號加上小寫的日誌層級。

"[INFO]: Operation completed" reformat .
! => "Operation completed (info)"

注意: 這道練習裡的所有字串都是 ASCII。之後的練習則會處理支援 Unicode 的字串處理。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟
Factor Exercism

準備好開始 日誌等級 了嗎?

註冊 Exercism,透過 47 個概念163 個練習 和真人引導來學習並精通 Factor,全部免費。