gpt4 book ai didi

haskell - 在 ghci 中工作,但不在文件中

转载 作者:行者123 更新时间:2023-12-03 14:50:00 25 4
gpt4 key购买 nike

当我在加载 putStrLn $ showManyP "%d" 10 之类的文件后在 ghci 中尝试某些操作时
它有效,但为什么当我将它写入文件时它不起作用main = putStrLn $ showManyP "%d" 10
它给出了这个错误

printf.hs:37:19:
Ambiguous type variable `a0' in the constraints:
(Format a0) arising from a use of `showManyP' at printf.hs:37:19-27
(Num a0) arising from the literal `10' at printf.hs:37:34-35
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `($)', namely `showManyP "%d" 10'
In the expression: putStrLn $ showManyP "%d" 10
In an equation for `main': main = putStrLn $ showManyP "%d" 10
Failed, modules loaded: none.

实际文件从这里开始:
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
import Data.List (intercalate,isPrefixOf)
class Showable a where
showManyP :: String -> a

instance Showable String where
showManyP str = str

instance (Showable s,Format a) => Showable (a->s) where
showManyP str a = showManyP (format str a)

class Format a where
format :: String -> a -> String

instance Format String where
format str a = replace "%s" str a

instance Format Char where
format str a = replace "%c" str [a]

instance Num a=>Format a where
format str a = replace "%d" str (show a)

replace :: String -> String -> String -> String
replace f str value = intercalate value $ split str f

split :: String -> String -> [String]
split [] f = [[]]
split str [] = [str]
split str@(x:xs) f | isPrefixOf f str = [[],drop (length f) str]
| otherwise = let (y:ys) = split xs f
in [x:y] ++ ys

最佳答案

在 ghc 中,当您输入像 10 这样的数字常量时, 它可以是 Num 的实例的任何类型.如果没有额外的类型约束,则为未定实例,必须提供特定类型;即(10 :: Int) . Ghci 是交互式的,必须为数字添加类型会很痛苦,因此它可以帮助您假设,在没有其他类型约束的情况下,看起来像整数的东西的类型是 Integer . GHC 用户指南 2.4.5. Type defaulting in GHCi 对此进行了解释。

根据“2010 Haskell 报告”,在 4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations ,有一个default允许您在编译模块中利用此行为的关键字。

关于haskell - 在 ghci 中工作,但不在文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7799345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com