2017-04-23 78 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

謝謝,這工作。 –