Match Pattern Arrays

Haskell provides a Data.Array.IArraytype of Arrayimmutable arrays. This allows the use of arrays inside functional code. Is it possible to map Arrayto templates, just as it is possible for lists?

I want the following code to work ...

function :: Ix a => Array a b -> ...

function [| x |]         = ... -- matches if arg has one element
function [| x, y |]      = ... -- matches if arg has two elements
function [| x, ..., y |] = ... -- matches if arg has more than 3 elements and
                               -- binds the first and last element with x and y

Note: this function exists in Rust, see https://doc.rust-lang.org/book/slice-patterns.html

+4
source share
2 answers

I am going to answer this for Data.Vectoror Data.Vector.Unboxedbecause I do not think the question really makes sense in terms of multidimensional Data.Array.IArray...

- ViewL ViewR Data.Sequence. ,

data ViewL a
    = EmptyL        -- ^ empty vector
    | a :< Vector a -- ^ leftmost element and the rest of the vector

data ViewR a
    = EmptyR        -- ^ empty vector
    | Vector a :> a -- ^ rest of the vector and the rightmost element

viewl :: Vector a -> ViewL a
viewl v | null v = EmptyL
        | otherwise = head v :< tail v 

viewr :: Vector a -> ViewR a
viewr v | null v = EmptyR
        | otherwise = init v :> last v 

viewlr :: Vector a -> (ViewL a, ViewR a)
viewlr v = (viewl v, viewr v) -- or `viewl &&& viewr` if you like Control.Arrows

ViewPatterns:

function :: Vector a -> ...
function (viewl -> x :< EmptyL)      = ... -- matches if arg has one element
function (viewl -> x :< y:< EmptyL)  = ... -- matches if arg has two elements
function (viewlr -> (x :< _, _ :> y) = ... -- matches `x` and `y` to the first and
                                           -- last elements
function (viewlr -> (x :< _ :< _ :< _, _ :> y) = ... -- matches if arg has more
                                                     -- than 3 elements and binds 
                                                     -- the first and last element
                                                     -- with x and y

tail init O (1) Data.Vector, , .

+1

-, , Haskell .

:

import Data.Array.IArray
import Data.Ix

foo arr
  | first == last = print x      -- single element case
  | otherwise     = print (x,y)  -- more than one element case
  where (first,last) = bounds arr
        x = arr ! first
        y = arr ! last
+2

Source: https://habr.com/ru/post/1649716/


All Articles