How to define function only for old versions in GHC?

有些话、适合烂在心里 提交于 2019-12-18 06:59:17

问题


I have a code that uses the fromRight function defined circa GHC 8.2. But I need to downgrade to GHC 8.0.2, which gives an error about Variable not in scope: for fromRight

I was wondering if it possible and how to add the missing definition

fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b

so that it is only used when I use an GHC version than 8.2.1?


回答1:


You can always write

import Prelude hiding (fromRight)

which is valid even if fromRight does not exist in Prelude. Therefore, if you want to write a module which is compatible with both old and new versions of Prelude, you can simply choose to ignore the new fromRight function, and always use the one in your library.




回答2:


Usually, when you're wondering about a library function, you should use CPP.

{-# language CPP #-}

#if !MIN_VERSION_base (4,10,0)
fromRight :: ...
#endif

The MIN_VERSION_... macros used to be provided by Cabal; now they're provided by GHC. If you want to use them with sufficiently old versions of GHC, you'll need to use Cabal (using either cabal-install or stack).


Before you go to the trouble of doing this, note that there are several packages with names ending in -compat that do all the work for you. In this case, you can use the fromRight from Data.Either.Compat in the base-compat package. Then you don't have to care whether you're using a new enough base library.



来源:https://stackoverflow.com/questions/47065477/how-to-define-function-only-for-old-versions-in-ghc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!