I'm trying to run the BinaryDerive.hs script as per the instructions in the Data.Binary doc, which states:
To derive the instance for a type,
load this script into GHCi, and bring
your type into scope. Your type can
then have its Binary instances derived
as follows:
$ ghci -fglasgow-exts BinaryDerive.hs
*BinaryDerive> :l Example.hs
*Main> deriveM (undefined :: Drinks)
However when I try to follow those instructions I get:
c:\Scripts\Haskell>$ ghci -fglasgow-exts BinaryDerive.hs
*BinaryDerive> :l TemperatureRecord.hs
[1 of 1] Compiling TemperatureRecord (TemperatureRecord.hs, interpreted )
Ok, modules loaded:TemperatureRecord.
*TemperatureRecord> deriveM (undefined :: TemperatureRecord)
(interactive):1:0: Not in scope: 'deriveM'
I am assuming that there is an additional step that was not specified that a beginner, like myself would not be aware of. It seems the root of the problem is that loading the TemperatureRecord takes BinaryDerive out of scope. Anyone have any ideas?
My understanding of ghci's loading/namespacing mechanisms is full of holes, but since nobody else has answered, here are some guessses:
Try :m + BinaryDerive after :l Example.hs
Add import BinaryDerive at the top of Example.hs
Don't add module TemperatureRecord where at the top of Example.hs
try
$ ghci -fglasgow-exts
Prelude> :l BinaryDerive TemperatureRecord
the .hs's are not necessary
Then you can access TemperatureRecord in a similar manner to this example (JSON Doc type taken from Real World Haskell, with some added Data and Typeable derives)
$ ghci -fglasgow-exts -XDeriveDataTypeable
Prelude> :l Binaryderive JSON
[1 of 2] Compiling JSON ( JSON.hs, interpreted )
[2 of 2] Compiling BinaryDerive ( Binaryderive.hs, interpreted )
Ok, modules loaded: BinaryDerive, JSON.
*BinaryDerive> deriveM (undefined::JSON.Doc)
instance Binary JSON.Doc where
put Empty = putWord8 0
put (Char a) = putWord8 1 >> put a
put (Text a) = putWord8 2 >> put a
put Line = putWord8 3
put (Concat a b) = putWord8 4 >> put a >> put b
put (Union a b) = putWord8 5 >> put a >> put b
get = do
tag_ <- getWord8
case tag_ of
0 -> return Empty
1 -> get >>= \a -> return (Char a)
2 -> get >>= \a -> return (Text a)
3 -> return Line
4 -> get >>= \a -> get >>= \b -> return (Concat a b)
5 -> get >>= \a -> get >>= \b -> return (Union a b)
_ -> fail "no parse"
Thanks everyone for the answers. I tried both of them and neither worked, however, the answers I saw did lead me too a solution.
$ ghci -fglasgow-exts -XDeriveDataTypeable
Prelude> :l Binaryderive TemperatureRecord
Prelude> :m Binaryderive TemperatureRecord
Prelude BinaryDerive TemperatureRecord>deriveM (undefined :: TemperatureRecord)
The above worked for me. However, I am not using that solution in practice. I am working on getting a more automatic solution to work. Anyway thanks for helping me get something that works.
Related
The program (Main.hs, found on SO) looks like this
import Control.Monad.Random
main :: IO ()
main = do
gen <- getStdGen
let values = evalRand diceSums gen
print . take 10 $ values
-- Generate sums from rolling two dice
diceSums :: RandomGen g => Rand g [Int]
diceSums = do
xs <- dieRolls
ys <- dieRolls
return $ zipWith (+) xs ys
-- Single die roll function.
dieRolls :: RandomGen g => Rand g [Int]
dieRolls = getRandomRs (1, 6)
I then run
stack ghci
Prelude> :l Main.hs
[1 of 1] Compiling Main ( Main.hs, interpreted )
Ok, one module loaded.
*Main> main
<interactive>:2:1: error:
* Variable not in scope: main
* Perhaps you meant `min' (imported from Prelude)
*Main> :t dieRolls
<interactive>:1:1: error: Variable not in scope: dieRolls
If I try and compile I get
ghc Main.hs
[1 of 1] Compiling Main ( Main.hs, Main.o )
Main.hs:1:1: error:
The IO action `main' is not defined in module `Main'
What am I doing wrong?
Might it be that stack is insisting on you adding the module declaration at the top of the module,
module Main where
(this seems related, though according to it, without the declaration, main should still be available -- though dieRolls indeed shouldn't.)
Not sure why main doesn't work, but the correct way to run main function from GHCi is :main. This way you can pass arguments to your program.
:type is not enough because the expression I want might include locally defined variables like things assigned with <-, let or where. Typed holes (replacing the expression with _ and loading with ghc) are close, but they give you what's accepted there, which might be more general than the expression you're curious about.
I thought I found the jackpot with :type-at, but I can't get it to work like I'd hope. With this file, named "thing.hs":
something :: ()
something = ()
main :: IO ()
main = return something
This is the result I get when using :type-at:
> :set +c
> :l thing.hs
[1 of 1] Compiling Main ( thing.hs, interpreted )
Ok, one module loaded.
Collecting type info for 1 module(s) ...
> :type-at thing.hs 5 8 5 13 -- "return" on last line
<no location info>: error: not an expression: ‘’
> :type-at thing.hs 5 1 5 4 -- "main" on last line
:: IO ()
> :type-at thing.hs 5 15 5 23 -- "something" on last line
<no location info>: error: not an expression: ‘’
That's basically the same as using :type. I was hoping I'd even be able to pass it the span for return something and get Monad a => a () or IO (). Would be even cooler if one could select between seeing the type of the expression alone and the type of the expression "at that point" (after being restricted by the type that would appear with a type hole), but either would be fine.
When I try :type-at thing.hs 5 8 5 14, I get :: () -> IO (). :type-at thing.hs 5 14 5 24 also works, as does :type-at thing.hs 5 14 6 1.
So, the right bound should be the cell one past the end of the expression.
Sometimes one can simply use a typed hole in front of the expression you are curious about works, using the hole as if it were a function. For instance
return (f 3)
---->
return (_ (f 3))
In this way, the hole will be typed with something like WantedType -> OtherType, where WantedType is the type of f 3.
This is not ideal, though, since the hole will prevent type inference to do its job. I.e., sometimes the type of f 3 is polymorphic, and its context forces it to be instantiated. For instance, 4 + length [] makes 4 to be Int, even if it can be of any Num type. Using (_ 4) + length [] introduces a function between the arbitrary Num type (which will get defaulted to Integer) and the needed Int, making type inference misbehave.
Instead, an alternative could be to use the translation
return (f 3)
------>
return (f 3 `asTypeOf` _)
This should play better with the type inference, and return the right™ type.
Of course, figuring out how :type-at works should be better. Still, the type hole trick is not too inconvenient when you have an editor already open at the spot.
I believe #chi answer can be improved (by avoiding the type inference issue ) by using a Dummy unary type constructor which does not implement the Show typeclass and using it with the print function :
someExpressionWeSearchType = Right $ Just (1 , ["Foo"] , getLine)
data Dummy a = Dummy a
main = do
putStrLn "Here we go"
--some code here...
let exp = someExpressionWeSearchType
--Debug stuff =>
print $ Dummy exp
-- other code here
putStrLn "Done"
This gives the following result when loaded :
Prelude> :l test.hs
[1 of 1] Compiling Main ( test.hs, interpreted )
test.hs:11:3: error:
* No instance for (Show
(Dummy (Either a0 (Maybe (Bool, [[Char]], IO String)))))
arising from a use of `print'
* In a stmt of a 'do' block: print $ Dummy exp
In the expression:
do putStrLn "Here we go"
let exp = someExpressionWeSearchType
print $ Dummy exp
putStrLn "Done"
In an equation for `main':
main
= do putStrLn "Here we go"
let exp = ...
print $ Dummy exp
....
|
11 | print $ Dummy exp
| ^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
So we can see that type inside the Dummy : Either a0 (Maybe (Bool, [[Char]], IO String))
When I'm developing some data analyses pipelines in haskell, it often would be useful to preload variable state into GHCi upon loading.
What I end up doing now is copy and pasting parts of a script line-by-line in emacs just to test and check the output of some intermediate processing. I can't even bulk copy-paste code because the line breaks don't get transferred (at least in emacs Interactive-Haskell mode)
Is there a way to do this?
EDIT: simply loading/reloading a .hs file doesn't do the trick because afaik there's no way to have "<-" bindings at the top level.
I suggest you take a look at foreign-store. It allows you to refer to variables by numbers, which persists through reloads. Here is an example:
λ: :set -XScopedTypeVariables
λ: import Foreign.Store
λ: st <- newStore "example"
Loading package foreign-store-0.2 ... linking ... done.
λ: readStore st
"example"
λ: st
Store 0
λ: :r
Ok, modules loaded: none.
λ: st
<interactive>:8:1:
Not in scope: ‘st’
Perhaps you meant ‘fst’ (imported from Prelude)
λ: Just (st :: Store String) <- lookupStore 0
λ: readStore st
"example"
Alternatively, you can also put all your definitions in a single hs file and only reload that. You can use unsafePerformIO to get around the restriction that you cannot use <- at the top-level. I think that is ok in this case, since your only using it for interactive anyway:
module Example where
import System.IO.Unsafe
example :: String
example = "example"
file :: String
file = unsafePerformIO $ readFile "/tmp/example.hs"
There are two main ways to do this:
Use the :l [filename] GHCi command to reload a file without exiting GHCi.
Write the variables in your ~/.ghci file, which will be loaded when GHCi is opened.
If you don't know what to put into ~/.ghci, here's what I have in mine:
:set prompt "\955 "
:set prompt2 "| "
:def hoogle \x -> return $ ":!hoogle --info \"" ++ x ++ "\""
let f `on` x = \a b -> (f a) `x` (f b)
let break (f,g) = \a -> (f a, f g)
I am use org-mode blogging, I use org-babel to evaluate the code as following :
#+BEGIN_SRC haskell
import Data.Function (fix)
f :: Int -> Int
f = (+ 1)
main :: IO ()
main = do
putStrLn $ show $ f 1
#+END_SRC
#+RESULTS:
: <interactive>:9:25: Not in scope: ‘f’
I found the org-babel for haskell use infer-haskell mode to start session and eval the code. I also say the session was created, and if I don't define the function but directly putStrLn "hello" , it works.
hope anyone can fix the bug :)
In this article, Yoshinari Nomura describes a way to evaluate Haskell blocks using runhaskell via a Ruby script. I do not understand japanese, so I cannot translate the details, but the method has allowed me to run haskell blocks without having to write specifically for the interpreter.
#+BEGIN_SRC haskell
import Data.Function (fix)
f :: Int -> Int
let f = (+ 1)
main :: IO ()
main = do
putStrLn $ show $ f 1
#+END_SRC
#+RESULTS:
: 2
Org's babel mode is running the Haskell code with ghci. In ghci you are required to use let to declare functions.
I'm currently in the process of solving euler problems to improve in Haskell. Though, my attempt at solving problem n° 43 produces no output.
Just to be clear, I'm not asking for help on the "problem algorithmic" part, even if I'm wrong. I'm specifically asking for help on the Haskell part.
So, I divided my attempt into simple functions. First I build a list holding all 0-9pandigital numbers, then I define functions to cut those numbers into the interesting part and finally I filter only the correct ones:
import Data.List
main = print $ foldl1 (+) goodOnes
pands = [read x :: Integer | x <- permutations "0123456789", head x /= '0']
cut3from :: Integer -> Integer -> Integer
cut3from x n = mod (div x nd) 1000
where
l = fromIntegral $ length $ show x :: Integer
nd = 10 ^ (l - 3 - n)
cut :: Integer -> [Integer]
cut x = map (cut3from x) [1..7]
testDiv :: Integral a => [a] -> Bool
testDiv l = and zipped
where
zipped = zipWith mult l [2, 3, 5, 7, 11, 13, 17]
mult :: Integral a => a -> a -> Bool
mult a b = mod a b == 0
goodOnes = filter (testDiv.cut) pands
Though, when compiling it (with -O2) and executing it, it outputs nothing. Even with +RTS -s.
I'd like advice on two points mainly:
why is this code wrong, how to improve it
how could I have debugged it myself
as a side point, if you have advice on how to handle Integer and Ints easily, please post them. I find it troublesome to use both together.
But any other remark is welcome!
EDIT: it seems that GHCi slowly builds the result list goodOnes and is able to answer after a long time (only in GHCi, when compiled it's still as reported). That's certainly not a behaviour I can wish to observ in my programs. How could I fix that ?
EDIT2: it now works when compiled too (code unchanged). I'm puzzled about all those inconsistencies and would welcome any explanation!
EDIT3: semihappy ending: after a reboot, all went back to normal ~~
To answer "how could I have debugged it myself":
Check out ghci.
prompt$ ghci
GHCi, version 6.12.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Loading package ffi-1.0 ... linking ... done.
Prelude>
It's an interactive interpreter that allows you to:
load files and play with the contents
Prelude> :load myfile.hs
[1 of 1] Compiling Main ( myfile.hs, interpreted )
Ok, modules loaded: Main.
*Main> xyz "abc"
*Main> 3
type in definitions and use them
*Main> let f x = x + 3
evaluate expressions and see the results
*Main> f 14
17
inspect types and kinds
*Main> :t f
f :: (Num a) => a -> a
*Main> :k Maybe
Maybe :: * -> *
Make sure you test each of the little pieces before you test the whole shebang -- it's easier to find problems in small things than in big ones. Check out QuickCheck if you're into unit tests.
For the Ints vs. Integers issue, you could sidestep the issue by only using Integers (of course, they may be less efficient: YMMV). Data.List has functions prefixed with generic, i.e. genericLength which are quite useful.
Here's how I compiled and ran it:
prompt$ ghc euler43.hs
prompt$ ./a.out
<some number is printed out>