環境:
Mac OS X 10.4.10 (PPC)
bc 1.06
iTunes 7.2
タイトルがちょっとわかりづらかったかも。
{1, 2, 3 ... 999, 1000} のようなリスト内の数値を repeat 文を使わずに合計する方法です。
AppleScript's text item delimiters を " + " に設定し、リストを足し算の計算式に変換してから bc に渡します。
set numList to {1, 2, 3}
set asdlm to AppleScript's text item delimiters
set AppleScript's text item delimiters to " + "
try
set calcString to (numList as string)
set AppleScript's text item delimiters to asdlm
on error
set AppleScript's text item delimiters to asdlm
return
end try
do shell script "echo " & quoted form of calcString & " | bc"
iTunes で選択されたトラックのサイズ合計も素早く求めることができます。
tell application "iTunes"
set sizeList to (size of selection)
end tell
set asdlm to AppleScript's text item delimiters
set AppleScript's text item delimiters to " + "
try
set calcSize to sizeList as string
set AppleScript's text item delimiters to asdlm
on error
set AppleScript's text item delimiters to asdlm
end try
set calcString to "scale=3; ( " & calcSize & " ) / 1024 / 1024"
do shell script "echo " & quoted form of calcString & " | bc"
(本当はこのあとに数値の大きさを見ながら MB やら GB やらに換算するスクリプトが続かなければならないのですが、iTunes がどういった基準で切り上げ/切り捨てを行っているのかいまひとつ把握できていないため、ここには書かないでおきます。
試行錯誤を繰り返せば iTunes のウインドウに表示される数値と全く同じ結果を求めることは可能だと思います。)
参考: bc
追記
do shell script は文字列をシェルスクリプトとして実行しますが
文字列を AppleScript として実行する方法があるのをすっかり忘れていました。
はい、run script です。
set x to "(100 + 20 + 30) / 15"
run script x
do shell script を実行 > シェルを起動 > bc を起動 > 計算
よりも
run script を実行 > 文字列を AppleScript としてコンパイル > 計算
のほうが若干速いのかもしれませんね。勘ですが。
bc と AppleScript では割り算をしたときの結果表示のされ方が異なるので、スクリプトの目的やその日の気分、好き嫌いなどによって使い分けると幸せになれるかもしれません。
- bc
- 除算を行うとデフォルトでは計算結果を小数点以下切り捨てで表示する
- scale=2 などと記述することで小数点以下を何桁まで表示するか指示できる
- 不正な計算式のときエラーを返さず空文字を返す (※do shell script の場合)
- AppleScript
- 除算の結果をできる限り細かく表示しようとする
- 除算を行って割り切れても 10.0 のように小数点以下第一位まで表示する
- 不正な計算式のときエラーを返す