Advertisement
Guest User

Untitled

a guest
Oct 8th, 2016
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.27 KB | None | 0 0
  1. type array<'t, 'ndims> =
  2.     {
  3.         dims : int array
  4.         data : 't array
  5.    }
  6.  
  7. type ndims2 =
  8.    static member n with get() = 2
  9.    static member indexer (a:array<_, ndims2>) =
  10.        let indexImpl (i:int, j:int) = i + j*a.dims.[1]
  11.        indexImpl
  12.    static member eachindex (a:array<_, ndims2>) =
  13.        let l1 = a.dims.[0]
  14.        let l2 = a.dims.[1]
  15.        seq { for i in 0 .. l1 - 1 do
  16.                for j in 0 .. l2 - 1 do
  17.                    yield (i, j)  }
  18.  
  19. let inline indexer (a:array<_, 'ndims>) =
  20.     (^ndims : (static member indexer : array<_, ^ndims> -> _) a)
  21.  
  22. let inline eachindex (a:array<_, 'ndims>) =
  23.    (^ndims : (static member eachindex : array<_, ^ndims> -> _) a)
  24.  
  25. let inline get (a:array<_, 'ndims>) ind =
  26.     let i = indexer a
  27.     a.data.[i(ind)]
  28.  
  29. let inline set (a:array<_, 'ndims>) ind value =
  30.    let i = indexer a
  31.    a.data.[i(ind)] <- value
  32.  
  33. let inline mapi (f:int -> 't -> 'u) (a:array<'t, 'ndims>) =
  34.    let index = indexer a
  35.     // let res = ...
  36.     // ... some boilerplate
  37.    for ind in (eachindex a) do
  38.        let i = index ind
  39.        res.data.[i] <- f i a.data.[i]
  40.    res
  41.  
  42. let m1 : array<float, ndims2> =
  43.    {
  44.        dims = [|2; 2|]
  45.        data = [|1.; 0.; 0.; 1.|]
  46.    }
  47.  
  48. mapi (fun i x -> (i, x)) m1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement