]> gitweb.factorcode.org Git - factor.git/commitdiff
tensors: simplify using map-sum
authorJohn Benediktsson <mrjbq7@gmail.com>
Sun, 30 Jan 2022 21:20:47 +0000 (13:20 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sun, 30 Jan 2022 21:25:31 +0000 (13:25 -0800)
extra/tensors/tensors.factor

index 578bcd2e8e79c41c3f45eb9ce642c2d20ad391d5..ef2bc0ae708844fb1e74d645d345d22450c23d73 100644 (file)
@@ -57,7 +57,7 @@ PRIVATE>
 
 ! Construct a tensor with vec { 0 1 2 ... } and reshape to the desired shape
 : naturals ( shape -- tensor )
-    check-shape [ ] [ product [0..b) >float-array ] bi <tensor> ;
+    check-shape dup product [0..b) >float-array <tensor> ;
 
 ! Construct a tensor without initializing its values
 : (tensor) ( shape -- tensor )
@@ -76,8 +76,7 @@ PRIVATE>
 
 ! Flatten the tensor so that it is only one-dimensional
 : flatten ( tensor -- tensor )
-    dup shape>>
-    product { } 1sequence >>shape ;
+    dup shape>> product { } 1sequence >>shape ;
 
 ! outputs the number of dimensions of a tensor
 : dims ( tensor -- n )
@@ -294,7 +293,7 @@ METHOD: t% { number tensor } [ >float ] dip [ mod ] with t-uop ;
 
 ! Sum together all elements in the tensor
 syntax:M: tensor sum vec>> 0 <simd-slice>
-    [ simd-slice>> 0 [ sum + ] reduce ]
+    [ simd-slice>> [ sum ] map-sum ]
     [ end-slice>> sum ] bi + ;
 
 <PRIVATE
@@ -398,7 +397,7 @@ syntax:M: tensor sum vec>> 0 <simd-slice>
 :: final-vstack-shape ( seq -- shape )
     ! Compute the new second-to-last dimension
     seq first dims 2 - :> vdim
-    seq 0 [ shape>> vdim swap nth + ] reduce
+    seq [ shape>> vdim swap nth ] map-sum
     ! Combine it to create the new shape
     seq first shape>> clone :> new-shape
     vdim new-shape set-nth
@@ -421,7 +420,7 @@ PRIVATE>
     ! Compute the final shape
     [
         ! Compute the first dimension
-        [ 0 [ shape>> first + ] reduce 1array ]
+        [ [ shape>> first ] map-sum 1array ]
         ! Compute the other dimensions
         [ first shape>> rest ] bi  append
     ]