作者:制霸 | 来源:互联网 | 2023-02-05 19:57
我编写了一个小程序来查找数字的素数因子分解.一切似乎都在编译,除了main
函数,它抱怨无法找到Show1
实例.
{-# LANGUAGE DeriveFunctor #-}
module FactorAnamorphism where
import Data.Functor.Foldable
import Data.List
nextPrimeFactor :: Integer -> Maybe Integer
nextPrimeFactor n = find (\x -> n `mod` x /= 0) [2..(floor $ sqrt $ fromIntegral n)]
data ExprF r = FactorF Integer | MultF r r deriving (Show, Functor)
type Expr = Fix ExprF
factor :: Integer -> Expr
factor = ana coAlg where
coAlg fac = case (nextPrimeFactor fac) of
Just prime -> MultF prime (fac `div` prime)
Nothing -> FactorF fac
main :: IO ()
main = putStrLn $ show $ factor 10
日志:
% stack build
haskell-playground-0.1.0.0: build (lib + exe)
Preprocessing library haskell-playground-0.1.0.0...
Preprocessing executable 'factor-anamorphism' for
haskell-playground-0.1.0.0...
[1 of 1] Compiling FactorAnamorphism ( app/FactorAnamorphism.hs, .stack-work/dist/x86_64-osx/Cabal-1.24.2.0/build/factor-anamorphism/factor-anamorphism-tmp/FactorAnamorphism.o )
/Users/ian/proj/macalinao/haskell-playground/app/FactorAnamorphism.hs:22:19: error:
• No instance for (Data.Functor.Classes.Show1 ExprF)
arising from a use of ‘show’
• In the second argument of ‘($)’, namely ‘show $ factor 10’
In the expression: putStrLn $ show $ factor 10
In an equation for ‘main’: main = putStrLn $ show $ factor 10
-- While building package haskell-playground-0.1.0.0 using:
/Users/ian/.stack/setup-exe-cache/x86_64-osx/Cabal-simple_mPHDZzAJ_1.24.2.0_ghc-8.0.2 --builddir=.stack-work/dist/x86_64-osx/Cabal-1.24.2.0 build lib:haskell-playground exe:factor-anamorphism exe:haskell-playground-exe --ghc-options " -ddump-hi -ddump-to-file"
Process exited with code: ExitFailure 1
Li-yao Xia..
11
Show
for 的实例Fix
是:Show1 f => Show (Fix f)
,这就是编译器期望的原因Show1 ExprF
.
Show1
可以在base下找到Data.Functor.Classes
,并且有一个TH脚本可以Text.Show.Deriving
从deriving-compat中派生出来.
1> Li-yao Xia..:
Show
for 的实例Fix
是:Show1 f => Show (Fix f)
,这就是编译器期望的原因Show1 ExprF
.
Show1
可以在base下找到Data.Functor.Classes
,并且有一个TH脚本可以Text.Show.Deriving
从deriving-compat中派生出来.
在文件顶部添加`{ - #LANGUAGE TemplateHaskell# - }`,导入`Text.Show.Deriving`,在数据声明旁边添加`$(deriveShow1''ExprF)`.`deriving-compat`不仅仅是一个简单的compat库,因为`deriveShow1`提供的功能目前在其他任何地方都找不到,即使在最新的GHC上也是如此.