gpt4 book ai didi

haskell - 如何导出类型类?

转载 作者:行者123 更新时间:2023-12-04 13:59:15 25 4
gpt4 key购买 nike

我正在创建一个文件,Common.hs ,导出我常用的函数。它还用我喜欢的版本替换了一些 Prelude 的功能:

-- Common.hs
module Common
import qualified Prelude as Prelude
import qualified Data.Foldable as Foldable

sum = Foldable.sum -- I want to replace Prelude's sum
print = Prelude.print -- I want to export Prelude's print
type Int = Prelude.Int -- I want to export Prelude's Int
... etc (huge list) ...

这样,每当我创建一个新的 Haskell 文件时,我只需要导入 Common并用 -XNoImplicitPrelude 编译它:
-- Test.hs
import Common
main = print (sum [1,2,3]) -- will be the `sum` version I want

这种方法似乎有效,但我不知道如何导出类型类:
-- Test.hs
import Common
import Prelude (Show)

data Foo = Foo Int Int deriving Show

main = print (Foo 1 2)

请注意,我必须手动导入 Prelude's Show。是否可以制作 Common.hs导出吗?

最佳答案

您必须显式重新导出类型类(这意味着您还必须显式导出其他所有内容),即

你的前奏:

module CustomPrelude (
sum,
product,
Prelude.IO,
Prelude.String,
Prelude.print,
Prelude.Show,
Prelude.show,
(Prelude.$),
Prelude.Int,
(++)
)
where

import qualified Prelude
import Data.Foldable
import Data.Monoid

(++) :: Monoid m => m -> m -> m
(++) = mappend

用法:
{-# LANGUAGE NoImplicitPrelude #-}
module PreludeTest where

import CustomPrelude

data A x = A x x

instance Show x => Show (A x) where
show (A x y) = "A " ++ show x ++ " " ++ show y

main :: IO ()
main = print $ A (1::Int) 2

为了节省一些打字时间(并在编辑时保持理智),您可能想要这样做:
A) 将你的新序曲拆分成几个专门的文件
B)做模块导出,所以你不必明确地重复一切

例如。:
module CustomPrelude.Classes (Show,show,Functor,fmap, Monoid,mempty,mappend, Monad,return,(>>=))
where

import Data.Monoid
module CustomPrelude.Functions (
module ReExport,
Prelude.print,
Prelude.IO, -- ok these technically aren't functions, but I didn't want to make yet another module just for demonstration purposes
Prelude.String,
Prelude.Int,
(Prelude.$),
(++)
)
where

import qualified Prelude
import Data.Foldable as ReExport
import Data.Traversable as ReExport
import Data.Monoid as ReExport


(++) :: Monoid m => m -> m -> m
(++) = mappend
module CustomPrelude (
module P
)
where

import CustomPrelude.Classes as P
import CustomPrelude.Functions as P

请注意,您可以通过在导入时将重新导出的模块全部重命名为相同的名称来节省大量打字工作。

关于haskell - 如何导出类型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31928840/

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