I have some old code which used to compile, but now it doesn't. I worry I may have hit a package management snafu, and I'm really bad at dealing with that sort of thing. I've cut it down to a minimal failing example.
{-# LANGUAGE OverloadedStrings #-}
module Gremlin where
import Database.MySQL.Simple.Param
import qualified Data.ByteString as SB
foo :: Param x => [x]
foo = []
shoo :: [SB.ByteString]
shoo = foo
The error I get is
/.../Gremlin.hs:12:8:
No instance for (Param SB.ByteString) arising from a use of ‘foo’
In the expression: foo
In an equation for ‘shoo’: shoo = foo
But when I look at the source code for
module Database.MySQL.Simple.Param
(
Action(..)
, Param(..)
, inQuotes
) where
I see
import qualified Data.ByteString as SB
and
instance Param SB.ByteString where
render = Escape
{-# INLINE render #-}
Relevant version information may include
$ ghci --version
The Glorious Glasgow Haskell Compilation System, version 7.10.2
$ ghc-pkg latest mysql-simple
mysql-simple-0.2.2.5
$ ghc-pkg latest bytestring
bytestring-0.10.8.1
When I ask ghci
:info Param
I get a shorter list than the mysql-simple documentation would lead me to expect.
Prelude> :m + Database.MySQL.Simple.Param Data.ByteString
Prelude Database.MySQL.Simple.Param Data.ByteString> :info Param
class Param a where
render :: a -> Action
-- Defined in ‘Database.MySQL.Simple.Param’
instance Param [Char] -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Word -- Defined in ‘Database.MySQL.Simple.Param’
instance Param a => Param (Maybe a)
-- Defined in ‘Database.MySQL.Simple.Param’
instance Param Integer -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Int -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Float -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Double -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Bool -- Defined in ‘Database.MySQL.Simple.Param’
instance Param Action -- Defined in ‘Database.MySQL.Simple.Param’
but I suppose that only tells me the instances for what's locally in scope. I then do
Prelude Database.MySQL.Simple.Param Data.ByteString> :m +Data.Text
Prelude Database.MySQL.Simple.Param Data.ByteString Data.Text> :info Param
class Param a where
...
instance Param Text -- Defined in ‘Database.MySQL.Simple.Param’
...
Further investigation points to a potential source of trouble:
$ ghc-pkg describe mysql-simple
name: mysql-simple
version: 0.2.2.5
...
depends:
...
bytestring-0.10.6.0-6e8453cb70b477776f26900f41a5e17a
...
I'm guessing that the ByteString with the instance is from 0.10.6.0 and distinct from the version I get when write exactly the same import in my source file. If so, I'm a bit peeved at how much work I had to do to find that out: it would be great if "No instance for Foo" would add "even though there's an instance for a whole other Foo".
This is cabal hell, right? Can I make mysql-simple rebuild with the newer version? I tried ghc-pkg unregister mysql-simple and then cabal install mysql-simple, but to no avail.
What's a good repair strategy?
What's a good repair strategy?
I urge you to cabalize the code and use cabal sandbox or stack. It should prevent the issue in the first place. To repair, you should find out what package is installed twice (it seems to be bytestring) and unregister it.
I'm a bit peeved at how much work I had to do to find that out: it would be great if "No instance for Foo" would add "even though there's an instance for a whole other Foo".
I know what you feel. Fortunately it is already fixed, so you should get better error message from ghc-8
Related
In section 3.5.6 of the Curry tutorial (pdf), we are advised to use default rules to "regain control after a failed search". The following example is given. (For clarity I have added a type signature and curried the input.)
lookup :: k -> [(k,v)] -> Maybe v
lookup key (_++[(key,value)]++_ ) = Just value
lookup’default _ _ = Nothing
I can't get that to compile unless I replace the ’ with a '. Once I do, it behaves like this:
test> test.lookup 1 [(2,3)]
*** No value found!
Question 1: What is the default declaration for?
Why would you need to specify that a particular clause is the default one? Won't it be arrived at one way or another, once the others fail?
Question 2: How is it written? Should it be written at all?
If instead I drop the string 'default:
lookup :: k -> [(k,v)] -> Maybe v
lookup key (_++[(key,value)]++_ ) = Just value
lookup _ _ = Nothing
it behaves as intended:
test> test.lookup 1 [(2,3)]
Nothing
test>
Has the 'default syntax changed since the tutorial was written? Has it been removed altogether?
This is the code you are looking for. Yours was missing the preprocessor directive to allow default rules. And using the wrong quote character.
-- Use default rules
{-# OPTIONS_CYMAKE -F --pgmF=currypp --optF=defaultrules #-}
lookup :: k -> [(k,v)] -> Maybe v
lookup key (_++[(key,value)]++_ ) = Just value
lookup'default _ _ = Nothing
test_positive = lookup 2 [(2,3)] == Just 3
test_negative = lookup 1 [(2,3)] == Nothing
A default rule serves various purposes. Regaining control after a failed search is a particularly useful one, since you cannot check with equality whether an expression is a failure.
If you delete the option "-F", then the preprocessor is not invoked which explains the behavior.
The permission error is due to the fact that not all possible
intermediate representations of a Curry program are precompiled
in the Ubuntu package. Unfortunately, the "default rule translator"
of CurryPP requires one of these intermediate representations.
The Ubuntu/Debian package is intended only for using the
kernel of Curry. For extensions and more advanced tools,
I recommend to install PAKCS manually, e.g., the current release from
https://www.informatik.uni-kiel.de/~pakcs/download.html
If you already have Ubuntu, a simple make should be sufficient.
In the "official" scala REPL I can do
scala> import util.Random
scala> util.Random.nextInt
res0: Int => -306696783
but in Ammonite-REPL I get
# import util.Random
cmd3.sc:1: object Random is not a member of pack ammonite.util
import util.Random
^
Compilation Failed
So right now I have to use the scala. prefix to make it work in Ammonite:
# import scala.util.Random
# scala.util.Random.nextInt
res1: Int = 503117434
I'm kind of new to Scala so I don't get why would ammonite use a different util than the (for me) "official" util, so I would appreciate if anyone can provide a rationale for this.
And more specifically, Is there any way to make util to be scala.util instead of ammonite.util?
It's not that Ammonite is replacing a different util library for the normal Scala one, it's that the Ammonite namespace has it's own util package which has a whole bunch of methods specific to Ammonite. Perhaps it would be nicer if the developer had chosen a different name for his package, but this is not an issue specific to Ammonite. It is something you will run into all the time. When there is a clash of namespaces, your only option is to fully qualify the package name for the one you want. So what you actually did is a fine solution. You can find more about this here.
And btw, since there is no util.Random in the Ammonite package you can do this after your import--I tested and this is a cut and paste from my terminal:
# Random.nextInt
res1: Int = 1045964363
When you do actually have a collision of method names, you can find a solution here
I want to switch between xmobar configurations on the fly by using key combinations. I have naively tagged the following onto my other key mods:
, ((controlMask, xK_l), xmproc <- spawnPipe "/usr/bin/xmobar /home/tony/.xmobarLrc")
, ((controlMask, xK_w), xmproc <- spawnPipe "/usr/bin/xmobar /home/tony/.xmobarWrc")
and the compiler barfs at <-. You can probably read my intention in the code. I am no Haskell expert and I'm slowly building up the environment I want by using a lego approach, but that has failed me here.
Where am I going wrong?
TIA
Well, it's quite complicated to do what you want. You can use the extensible state module from the xmonad-contrib library.
For that, you have to add a LANGUAGE pragma at the top of your xmonad configuration file:
{-# LANGUAGE DeriveDataTypeable #-}
You need it to derive the Typeable instance for the data type that stores the xmobar handle.
newtype XMobarHandle = XMobarHandle { xmhandle :: Maybe Handle } deriving Typeable
instance ExtensionClass XMobarHandle where
initialValue = XMobarHandle Nothing
Now you can define the key-binding, which retrieves the current xmobar handle from the extensible state, closes it if it is not Nothing, spawns a new one and puts it into the state.
((controlMask, xK_l), do
mh <- xmhandle `fmap` XS.get
maybe (return ()) (io . hClose) mh
xmproc <- spawnPipe "/usr/bin/xmobar /home/tony/.xmobarLrc"
XS.put $ XMobarHandle (Just xmproc)
)
You can create a function for the do block in the binding if you like. The binding for the other key is left as an exercise!
To make it compile, you still need the import statements for the modules used in this code. (I may have forgotten one, though!)
import XMonad.Util.Run
import System.IO
import qualified XMonad.Util.ExtensibleState as XS
You have to edit your logHook as well. There you have to extract the handle from extensible state just like in the keybind and give it as a parameter to the function xmobarlog.
I'm looking for a way to dynamically define functions in Haskell, or for Haskell's idiomatic equivilent of which I'm clearly not aware.
The scenario is as follows: I have a tagWithAttrs function that generates new functions based on the provided String argument. The definition looks something like this:
tagWithAttrs :: String -> ([(String, String)] -> [String] -> String)
tagWithAttrs tagName = [...] -- Implementation ommited to save room.
h1 :: [(String, String)] -> [String] -> String
h1 = tagWithAttrs "h1"
main :: IO ()
main = putStrLn $ h1 [("id", "abc"), ("class", "def")] ["A H1 Test"]
-- Should display '<h1 id="abc" class="def">A H1 Test</h1>'.
So far so good. But the line in which I assign h1 is one of many, since I'd have to do that for every single HTML tag I'm defining. In Python, I'd loop over a list of the HTML tag names, inserting each respective result from tag_with_attrs into the dictionary returned by globals(). In short, I'd be inserting new entries into the symbol table dynamically.
What is the Haskell equivilent of this idiom?
Btw, I'm fully aware that I'm duplicating the work of many existing libraries that already do HTML tags. I'm doing this for a toy project, nothing more :)
EDIT: Some posted solutions are suggesting mechanisms that still rely on defining the end result tag functions one-by-one. This violates DRY, else I would have just done it how I was doing it. It's that DRY violation that I'm trying to side-step.
Haskell is statically typed, which means that all symbols must be type-checked at compile time. So that means you can't add entries into the symbol table at runtime.
What you want is meta-programming. Where code runs at compile time to generate other code (that you naturally and rightly feel lazy to type). That implies something like a macro system .
Haskell does not have macros, but there is template Haskell:
http://www.haskell.org/haskellwiki/Template_Haskell
As with macros, the idea is that you write a function that generates an
AST. The meta-function takes the name of the function you want to use (in your
case, div, ul, li etc) and generates the AST of a functional with that name.
A bit overkill, but if you really want to do it this is a relatively simple tutorial:
http://playingwithpointers.com/archives/615
Well, as you know Haskell is curried and functions are first class, so you really don't need any magic to do that. Just recognize that you can do stuff like:
import qualified Data.Map as M
import Data.Map (Map)
import Data.Text (Text)
type TagName = Text
type TagWithAttrs = Map TagName ([(String, String)] -> [String] -> String)
tagFuncs :: TagWithAttrs
tagFuncs =
M.fromList $
("h1", \xs ys -> zs) :
("h2", \xs ys -> zs) :
{- ... -}
[]
tagWithAttrs :: TagName -> [(String, String)] -> [String] -> String
tagWithAttrs = flip M.lookup tagFuncs
This is all regular efficient Haskell. Note: You may be tempted to define tagFuncs as a local value to tagWithAttrs by using a where clause. While this can make your code more beautiful it will also result in the map to be regenerated for each invocation of tagWithAttrs.
To dynamically insert things into the map you can make the map an argument of tagWithAttrs instead of a top level map. Another alternative is to use a concurrent variable like an MVar or (probably better) a TVar.
This can be done easily with some Template Haskell:
{-# LANGUAGE TemplateHaskell #-}
import Control.Monad (forM)
import Language.Haskell.TH
tagWithAttrs :: String -> ([(String, String)] -> [String] -> String)
tagWithAttrs tagName = undefined
$(forM ["h1", "h2", "h3"] $ \tag ->
valD (varP (mkName tag)) (normalB [| tagWithAttrs $(stringE tag) |]) [])
main :: IO ()
main = putStrLn $ h1 [("id", "abc"), ("class", "def")] ["A H1 Test"]
This generates declarations h1 = tagWithAttrs "h1", h2 = tagWithAttrs "h2", h3 = tagWithAttrs "h3", and so on. To add more, just add them to the list.
The code is a bit ugly since it's not possible to splice patterns in TH. Otherwise, we would have been able to write something like [d| $(mkName tag) = tagWithAttrs $(stringE tag) |]. Instead, we have to manually construct the declaration using TH combinators.
I think what I would do would be to define a data type for tags:
data Tag = H1 | H2 | H3 ...
deriving (Show, Eq, Ord, Enum, Bounded)
This is your single point of definition for all the tags that there are.
Then define a function that maps Tag values to the appropriate function:
tag :: Tag -> [(String, String)] -> [String] -> String
tag = tagWithAttrs . show
And then where you want to call h1, h2, h3, you instead call tag H1, tag H2, tag H3, etc.
Note that this is identical in verbosity to if you had defined functions tag_h1, tag_h2, tag_h3, etc; effectively you've just got slightly longer names (which happen to include a space). To me this is the ideal combination of DRY and "say what you mean". h1 doesn't seem like a function to me anyway; I'd actually much rather think that I was working with one function on a number of data items than that I had a giant set of functions.
If I was then unsatisfied with the speed of this (because the compiler probably won't optimize away all of the tagWithAttrs calls away) and I had determined that this was the "lowest hanging fruit" to speed up my application, I would look at memoizing tagWithAttrs or tag, but internally so as to keep the same interface. One quick possibility: pre-populate a map with all tags; you can use the Enum and Bounded instance to do this without explicitly re-listing all the tags (this is something you couldn't do with tags represented by functions or by strings). A side benefit of non-strict evaluation is that this will probably result in tagWithAttrs being evaluated exactly once for each tag that is actually used.
That would still leave a data-structure lookup on each tag call (unless the compiler is clever enough to optimise them away, which is not impossible). I doubt that would be the most significant performance bottleneck unless you've done some heavy optimisation of the rest of your program. To do all the lookups at compile time (without relying on the optimiser), I think you do need Template Haskell. I probably wouldn't go that far in this case, just because I sincerely doubt I would need it to go any faster (and I have way more available compute-time than me-time). But even if I was using Template Haskell to get the lookups done at compile-time I would prefer to not make it look like a separate top-level function for each tag; I just find "tags and a function that knows how to render tags" to be a more natural and flexible approach than "tags, which can be called to render themselves".
Write a simple code generator, input the list of tags you want, include the output as a module.
One last question for the evening, I'm building the main input function of my Haskell program and I have to check for the args that are brought in
so I use
args <- getArgs
case length args of
0 -> putStrLn "No Arguments, exiting"
otherwise -> { other methods here}
Is there an intelligent way of setting up other methods, or is it in my best interest to write a function that the other case is thrown to within the main?
Or is there an even better solution to the issue of cases. I've just got to take in one name.
args <- getArgs
case length args of
0 -> putStrLn "No Arguments, exiting"
otherwise -> do
other
methods
here
Argument processing should isolated in a separate function.
Beyond that it's hard to generalize, because there are so many different ways of handling arguments.
Here are some type signatures that are worth considering:
exitIfNonempty :: [Arg] -> IO [Arg] -- return args unless empty
processOptions :: [Arg] -> (OptionRecord, [Arg]) -- convert options to record,
-- return remaining args
processOptionsBySideEffect :: [Arg] -> State [Arg] -- update state from options,
-- return remaining args
callFirstArgAsCommand :: [(Name, [Arg] -> IO ())] -> [Arg] -> IO ()
And a couple sketches of implementations (none of this code has been anywhere near a compiler):
exitIfNonempty [] = putStrLen "No arguments; exiting"
exitIfNonempty args = return args
callFirstArgAsCommand commands [] = fail "Missing command name"
callFirstArgAsCommand commands (f:as) =
case lookup f commands in
Just f -> f as
Nothing -> fail (f ++ " is not the name of any command")
I'll leave the others to your imagination.
Is it in my best interest to write a function that the other case is thrown to within the main?
Yes. Moreover, you should build up a library of combinators that you can call on to process command-line argument easily, for a variety of programs. Such libraries undoubtedly already exist on Hackage, but this is one of those cases where it may be easier to roll your own than to learn somebody else's API (and it will definitely be more fun).
View Patterns might be helpful here.