# numpy - 数组 - haskell重现numpy

``````
import numpy as np

a = np.arange(1, 18)

b = a.reshape([-1, 2, 3])

# b =

#

# array([[[ 1, 2, 3],

# [ 4, 5, 6]],

#

# [[ 7, 8, 9],

# [10, 11, 12]],

#

# [[13, 14, 15],

# [16, 17, 18]]])

``````

``````
*Main> reshape23 [1..18]

[[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]],[[13,14,15],[16,17,18]]]

``````

``````
takeWithRemainder :: (Integral n) => n -> [a] -> ([a], [a])

takeWithRemainder _ [] = ([], [])

takeWithRemainder 0 xs = ([], xs)

takeWithRemainder n (x:xs) = (x : taken, remaining)

where (taken, remaining) = takeWithRemainder (n-1) xs

chunks :: (Integral n) => n -> [a] -> [[a]]

chunks _ [] = []

chunks chunkSize xs = chunk : chunks chunkSize remainderOfList

where (chunk, remainderOfList) = takeWithRemainder chunkSize xs

reshape23 = chunks 2 . chunks 3

``````

``````
reshape :: (Integral n) => [n] -> [a] -> [b]

reshape ns list = foldr (n acc -> (chunks n) . acc) id ns list

``````

``````
class Reshape (dimensions :: [Nat]) from to | dimensions from -> to where

reshape :: from -> to

``````

``` ```
``` ```
``` ```
``` 列表列表与数组不同，这是一个常见的误解，Haskell没有数组，你不得不处理列表Haskell生态系统中有两个数组库，其中一个是massivreshape类numpy的功能可以通过resize'函数实现： λ> 1 ... (18 :: Int) Array D Seq (Sz1 18) [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ] λ> resize' (Sz (3 :> 2 :. 3)) (1 ... (18 :: Int)) Array D Seq (Sz (3 :> 2 :. 3)) [ [ [ 1, 2, 3 ] , [ 4, 5, 6 ] ] , [ [ 7, 8, 9 ] , [ 10, 11, 12 ] ] , [ [ 13, 14, 15 ] , [ 16, 17, 18 ] ] ] ```
``` ```