gpt4 book ai didi

haskell - 列表最后一个元素的模式匹配

转载 作者:行者123 更新时间:2023-12-04 22:02:49 27 4
gpt4 key购买 nike

我们使用 (x:xs) 对第一个元素进行模式匹配,如下例所示:

head' :: [a] -> a  
head' xs = case xs of [] -> error "No head for empty lists!"
(x:_) -> x

有没有办法在最后一个元素上进行图案匹配?

最佳答案

如果您拥有GHC 6.10或更高版本,请使用view pattern

View patterns permit calling the view function inside the pattern and matching against the result:

size (view -> Unit) = 1
size (view -> Arrow t1 t2) = size t1 + size t2

That is, we add a new form of pattern, written

expression -> pattern

that means “apply the expression to whatever we're trying to match against, and then match the result of that application against the pattern.” The expression can be any Haskell expression of function type, and view patterns can be used wherever patterns are currently used.



head' 定义为

{-# LANGUAGE ViewPatterns #-}

head' :: [a] -> a
head' (last -> l) = l

它按您的预期工作。

λ> head' [3,5,7]
7
λ> head' []
*** Exception: Prelude.last: empty list

关于haskell - 列表最后一个元素的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54539981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com