2017-04-23 55 views
2

我写了一个小程序,以找到一个数的因式分解。一切似乎除了main功能,抱怨不能够找到一个Show1实例进行编译。没有实例(Data.Functor.Classes.Show1 ExprF)

{-# 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 

回答

6

Show的实例Fix是:Show1 f => Show (Fix f),这就是为什么编译器期望Show1 ExprF

Show1可以在Data.Functor.Classes的底下找到,并且有一个TH脚本可以从deriving-compat中导出Text.Show.Deriving

+0

感谢。请原谅我的无知,但我将如何调用模板Haskell脚本?另外,它看起来像派生compat是一个compat库 - 如果我在最新版本的GHCi上,我需要使用它吗? –

+0

加上'{ - #语言TemplateHaskell# - }'你的文件的顶部,进口'Text.Show.Deriving',加上'$(deriveShow1'ExprF)'旁边的数据声明。 '获得-compat'不仅仅是一个简单的COMPAT库的更多,如'deriveShow1'例如提供的功能不能被其他地方的那一刻发现,即使是最新的GHC。 –

+0

谢谢,这工作。 –