Created
September 7, 2012 06:37
-
-
Save eldesh/3663860 to your computer and use it in GitHub Desktop.
Unfolding on Array(fixed size memory block)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(*** | |
* Array, Vector 等の固定長データ構造を生成するために状態を持ちたい。 | |
* unfold すればよいが、要素を一つずつ連結するのはイヤ(重すぎる)なので 配列用unfold 作ってみた | |
* ***) | |
infixr 1 $ | |
fun f $ a = f a | |
structure Array = | |
struct | |
open Array | |
fun fst (f,_) = f | |
fun unfold n f e = | |
if n=0 then array (0, fst (f e)) (* FIXME: ダメもとで一つ目の要素を取り出してみる *) | |
else | |
let | |
val (x,e') = f e | |
val xs = array (n, x) (* 先頭に指定された値を使って初期化 *) | |
fun go i e = | |
if n=i then () | |
else | |
let val (x,e') = f e in | |
(update (xs, i, x); go (i+1) e') | |
end | |
in | |
(go 1 e'; xs) | |
end | |
end | |
val int = Int.toString | |
fun println s = print (s^"\n") | |
val _ = Array.app (println o int) $ Array.unfold 10 (fn i=> (i,i+1)) 0 | |
(* | |
- Array.unfold 10 (fn i=> (i,i+1)) 0; | |
val it = [|0,1,2,3,4,5,6,7,8,9|] : int array | |
*) | |
val _ = println "--------------------" | |
val _ = Array.app (println o int) $ Array.unfold 10 (fn i=> (i,i+2)) 0 | |
(* | |
- Array.unfold 10 (fn i=> (i,i+2)) 0; | |
val it = [|0,2,4,6,8,10,12,14,16,18|] : int array | |
*) | |
val _ = println "--------------------" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment