printfの自作
Posted feedbacks - Smalltalk
Squeak Smalltalk で。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | | printf |
printf := [:args |
| formStrm valsStrm outStrm |
formStrm := args first readStream.
valsStrm := args allButFirst readStream.
outStrm := String new writeStream.
[formStrm atEnd] whileFalse: [
| next width print scale format |
outStrm nextPutAll: (formStrm upTo: $%).
next := formStrm next.
width := scale := 0.
next ifNotNil: [
next isDigit ifTrue: [
formStrm back.
width := Integer readFrom: formStrm.
next := formStrm next].
next = $. ifTrue: [
scale := Integer readFrom: formStrm.
next := formStrm next]].
print := [:val |
| str |
str := val asString.
width := width max: str size.
outStrm nextPutAll: (str forceTo: width paddingStartWith: $ )].
format := [:float |
| str idx |
str := (scale > 0 ifTrue: [float asScaledDecimal: scale] ifFalse: [float]) asString.
(idx := str indexOf: $s) > 0 ifTrue: [str := str first: idx - 1].
str].
next caseOf: {
[$%] -> [outStrm nextPut: $%].
[$d] -> [print value: valsStrm next asInteger].
[$f] -> [print value: (format value: valsStrm next asFloat)].
[$o] -> [print value: (valsStrm next radix: 16)].
[$x] -> [print value: (valsStrm next radix: 8)].
[$c] -> [outStrm nextPut: valsStrm next asCharacter].
[$s] -> [outStrm nextPutAll: valsStrm next asString]} otherwise: []].
outStrm contents].
printf value: {'hoge %6.2f %6d %o %x %c %s %% fuga'. 1.234. 1234. 1234. 1234. 'a'. 'abc'}
"=> 'hoge 1.23 1234 4D2 2322 a abc % fuga' "
|


yappy
#4119()
[
C
]
Rating-2/20=-0.10
Rating-2/20=-0.10-0+
[ reply ]