【问题标题】:Non-exhaustive pattern error in recursive function递归函数中的非穷举模式错误
【发布时间】:2017-10-22 13:09:45
【问题描述】:

我正在尝试使用递归和高阶函数对列表的第一个元素执行某些操作,然后对列表中的所有其他元素执行操作,例如,将 3 添加到第一个、第三个、第五个......等。

我遇到的问题是它给了我non-exhaustive pattern 错误。任何帮助,将不胜感激。这是我到目前为止所拥有的:

applyToEveryOther :: (a -> b) -> [a] -> [b]
applyToEveryOther _ [] = []
applyToEveryOther f (x:y:xs) = f x : applyToEveryOther f xs

这些是我尝试过但没有帮助的一些附加行:

applyToEveryOther _ [x] = f x
applyToEveryOther f [x] = f x

【问题讨论】:

标签: list haskell recursion


【解决方案1】:

单元素案例也应该返回一个列表([b] 类型):

applyToEveryOther f [x] = [f x]

【讨论】:

  • 如果我对此还有其他问题......我是新手,不确定我是否会发新帖子
  • @loutej 绝对是一个新帖子! (我认为答案是f x : y : applyToEveryOther f xs,但它的格式会更好,并且作为新帖子对其他人更有用)。
【解决方案2】:

另一种不使用显式递归而仅使用高阶函数的解决方案:

import Data.List (cycle)

applyToEveryOther f = zipWith ($) (cycle [f, id])

cycle 创建一个无限的交替函数列表 fidfid 等。

zipWith ($) 将列表中的函数应用于输入列表的相应元素。

[(+1), id, (+1), id, (+1), id, (+1), id, ...]
[   1,  2,    3,  4,    5,  6,    7,  8     ]
=============================================
[   2,  2,    4,  4,    6,  6,    8,  8     ]

(提示:将函数列表分段应用于参数列表的问题,以及在 1HaskellADay twitter 提要上使用 zipWith ($)appeared recently 的解决方案。)

(我自己的劣质解决方案是使用Control.Applicative 中的ZipList 类型构造函数;应用在这里,它看起来像

import Control.Applicative

applyToEveryOther f xs = let fs = cycle [f,id]
                          in getZipList (ZipList fs <*> ZipList xs)

)

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多