How do I use a Haskell library function?
Solution 1
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.
Solution 2
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/
Solution 3
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)
Related videos on Youtube
Eric Wilson
Software developer, experienced in Java and Python in Linux environments, formerly a professor of mathematics. I'm a father of five children, and a husband of one wife.
Updated on February 01, 2020Comments
-
Eric Wilson about 4 years
I'm a Haskell newbie, trying to accomplish 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
andchr
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? -
Eric Wilson over 13 yearsI did check Hoogle, but didn't know what to do with the information that I received. Thanks.
-
hyiltiz over 4 yearsIs it considered bad practice to use
Data.Char.ord
there instead of importing it, esp. iford
is used only once? I understand it makes reading the program harder by "hiding" imports into the program body. -
Paul Johnson over 4 years@hyiltiz I suggest you ask that as a separate question, as its a complicated trade-off. Usual practice is to import common libraries unqualified unless they have name clashes (e.g.
import qualified Data.Map as M
).