You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在函数外部使用`with`?能否在函数签名中直接使用views与`with`?

解答

你尝试的写法不符合Idris语法规则:with是Idris为顶层函数定义提供的模式匹配扩展语法,不能直接嵌套在类型签名的case表达式中。不需要额外定义类型级函数,就可以实现你要的view匹配逻辑,正确实现方式如下:

直接在函数定义中使用with

import Data.List.Views

data Foo : List Nat -> Type where
  -- 可根据需求补充Foo的构造子定义
  MkFoo : Foo xs

bar : Foo xs -> Nat -- 这里换成你实际需要的返回类型
bar xs with (snocList xs)
  bar xs | Empty => ?rhs_empty
  bar xs | Snoc y ys rec => ?rhs_snoc

在let代码块中使用view匹配

如果你不想用with语法,也可以直接在let中绑定view结果再做模式匹配:

bar : Foo xs -> Nat
bar xs = let snocView = snocList xs in
  case snocView of
    Empty => ?rhs_empty
    Snoc y ys rec => ?rhs_snoc

返回类型依赖匹配结果的实现

如果你的函数返回类型需要根据列表拆分结果变化,直接使用依赖case即可,不需要额外定义独立的类型级函数:

bar : Foo xs -> (snoc : SnocList xs) -> case snoc of
  Empty => Nat -- 空列表场景的返回类型
  Snoc y ys rec => Int -- 非空snoc结构场景的返回类型
bar xs snoc with (snocList xs)
  bar xs snoc | Empty = 0
  bar xs snoc | Snoc y ys rec = 1

内容的提问来源于stack exchange,提问作者joel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:27:03