How do I use a Haskell library function?
I'm a Haskell newbie, trying to accompl开发者_运维知识库ish a Caesar cipher exercise.
In a .hs
file, I defined the following function:
let2int :: Char -> Int
let2int c = ord c - ord 'a'
Then I attempt to load this into GHCi by typing :l caeser.hs
and I get the following error message:
[1 of 1] Compiling Main ( caeser.hs, interpreted )
caeser.hs:2:12: Not in scope: `ord'
caeser.hs:2:20: Not in scope: `ord'
From the book I was using, I had the impression that ord
and chr
were standard functions for converting between characters and integers, but it seems evident that I need to "import" them or something. How is this done?
They are standard functions but you need to import them from the right module first. Add
import Data.Char
to ceaser.hs and it should work.
See also http://www.haskell.org/ghc/docs/latest/html/libraries/index.html for the full set of libraries that ship with the compiler.
In "Haskell 2010", ord
lives in Data.Char
So you'll want import Data.Char
or import Data.Char (ord)
In "Haskell 98", ord
can be found in the module Char
.
A great tool for finding functions and their modules is
http://www.haskell.org/hoogle/
If you use hoogle to search for ord you'll see that function lives in / is exported by the Data.Char module. So just import this module:
import Data.Char
Learn to use hoogle. Many of the SO Haskell questions asked are a result of people not knowing about Hoogle... and sometimes they must not know about Google either (not to discourage you from asking, but do use hoogle).
In the future, for larger libraries that might have conflicting names with existing functions you can either limit your import to just the function you care about:
import Data.Char (ord)
Or import it qualified
:
import qualified Data.Char as C
...
func x y = C.ord x - C.ord y
(a third method, using hiding
, works but I detest that method)
精彩评论