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

如何解决使用Hakyll.loadSnapshot时的"No instance for (Typeable a0)"错误

问题描述

我正尝试为站点添加功能,以展示同一文章的不同版本。例如,若源目录包含mypost/version/1、mypost/version/2、mypost/version/3,希望将所有版本复制到生成站点,同时新增路径mypost/version/latest。

为实现该功能,我编译每个文章版本并使用saveSnapshot创建快照,遍历mypost/version目录找到最新版本,再获取其编译快照复制到目标路径。

我编写了如下代码,将loadSnapshot的输出传入文件复制编译器:

loadSnapshotAndCopy :: Snapshot -> Compiler (Item CopyFile)
loadSnapshotAndCopy snapshot = do
  identifier <- getUnderlying
  item <- loadSnapshot identifier snapshot
  provider <- compilerProvider <$> compilerAsk
  makeItem $ CopyFile $ resourceFilePath provider (itemIdentifier item)

但运行时出现错误:

• No instance for (Typeable a0)
        arising from a use of ‘loadSnapshot’
    • In a stmt of a 'do' block:
        item <- loadSnapshot identifier snapshot
      In the expression:
        do identifier <- getUnderlying
           item <- loadSnapshot identifier snapshot
           provider <- compilerProvider <$> compilerAsk
           makeItem
             $ CopyFile $ resourceFilePath provider (itemIdentifier item)
      In an equation for ‘loadSnapshotAndCopy’:
          loadSnapshotAndCopy snapshot
            = do identifier <- getUnderlying
                 item <- loadSnapshot identifier snapshot
                 provider <- compilerProvider <$> compilerAsk
                 ....
    |
248 |   item <- loadSnapshot identifier snapshot
    |           ^^^^^^^^^^^^

已知loadSnapshot的类型为loadSnapshot :: (Binary a, Typeable a) => Identifier -> Snapshot -> Compiler (Item a),推测编译器无法满足约束条件,请问如何解决该问题以正常使用loadSnapshot?

解决方案

问题核心是编译器无法推断loadSnapshot要加载的快照具体类型a——你的代码只用到了itemIdentifier,没有使用item的内容,导致类型信息丢失,无法满足Typeable约束。

可以通过以下两种方式解决:

1. 显式指定快照类型

既然不需要item的内容,只需要它的标识符,可直接指定a为满足Binary和Typeable约束的类型(比如空元组()):

loadSnapshotAndCopy :: Snapshot -> Compiler (Item CopyFile)
loadSnapshotAndCopy snapshot = do
  identifier <- getUnderlying
  -- 显式声明加载的快照类型为 ()
  item <- loadSnapshot identifier snapshot :: Compiler (Item ())
  provider <- compilerProvider <$> compilerAsk
  makeItem $ CopyFile $ resourceFilePath provider (itemIdentifier item)

2. 使用loadSnapshotRaw替代

如果完全不需要快照内容,仅需获取资源标识符,改用loadSnapshotRaw更合适——它不需要类型约束,直接返回资源的Identifier:

import Hakyll.Core.Snapshot (loadSnapshotRaw)

loadSnapshotAndCopy :: Snapshot -> Compiler (Item CopyFile)
loadSnapshotAndCopy snapshot = do
  identifier <- getUnderlying
  rawItem <- loadSnapshotRaw identifier snapshot
  provider <- compilerProvider <$> compilerAsk
  makeItem $ CopyFile $ resourceFilePath provider rawItem

原理说明

loadSnapshot需要明确的类型a来反序列化快照数据,但你的代码未使用快照内容,编译器无法自动推断a。显式指定类型或使用无类型约束的loadSnapshotRaw,都能让编译器获得足够的类型信息,解决约束缺失问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:25:24