[英]Pattern matching of Arrays
Haskell在Data.Array.IArray
提供了不可Data.Array.IArray
的類型Array
。 這允許在功能代碼內部使用數組。 是否可以將Array
與模式匹配,就像列表一樣?
我想下面的代碼工作...
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
注意:此功能以Rust語言存在,請參閱https://doc.rust-lang.org/book/slice-patterns.html
首先,請注意,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
我將針對Data.Vector
或Data.Vector.Unboxed
回答這個問題,因為我認為對於多維Data.Array.IArray
而言,這個問題真的沒有Data.Array.IArray
...
您可以在Data.Sequence
中執行類似於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
是Data.Vector
O(1)切片,因此懶惰地僅根據需要查看向量中的所有元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.