2026-10-05
Ring.hs
import Data.Array
data Ring = Ring Int Int (Array Int Char)
push :: Char -> Ring -> Ring
push c (Ring start size buf)
| size < cap = Ring start (size + 1) (buf // [((start + size) `mod` cap, c)])
| otherwise = Ring ((start + 1) `mod` cap) size (buf // [(start, c)])
where
cap = rangeSize (bounds buf)
main :: IO ()
main = do
let Ring start _ buf = foldl (flip push) (Ring 0 0 (listArray (0, 2) "...")) "abcde"
print (start, elems buf)
これは何を出力するでしょうか?
Answer
(2,"dec") です。
Ring start size buf の start は一番古い要素の位置、size は入っている要素の数で、容量 cap は配列の大きさの3です。push は、満杯でなければ start + size を cap で割った余りの位置に書きます。満杯なら一番古い要素がある start に上書きし、start を1つ進めます。
foldl (flip push) は文字列の先頭から順に push するので、a b c は位置0, 1, 2に入って満杯になります。続く d は最古の a がある位置0に書かれて start が1になり、e は位置1の b に上書きされて start が2になります。
elems は配列を位置の順に並べるので "dec" です。古い順に読むなら、start の位置2から c d e の順になります。