How to change xmobar configuration on the fly - configuration

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.

Related

How can I make scala's ammonite use scala.util instead of ammonite.util as default for util?

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

How has instance (Param B.ByteString) managed to vanish?

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

what I do for these conditions to follow FP?

I'm reading FP and I have two basic questions:
FP says function should take one input and gives single output. So what should I do with void methods? It doesn't return anything right?
FP says function should have single
resresponsibility, then how do we handle log statements inside the method? That doesn't violate the rule?
Wish to know how they handle these things in Scala, Haskell.
Thanks in advance.
I'm assuming you're reading a book called "Functional Programming", although it would help to know who the author is as well. In any case, these questions are relatively easy to answer and I'll give my answers with respect to Haskell because I don't know Scala.
So what should I do with void methods? It doesn't return anything right?
There are no void methods in a pure functional language like Haskell. A pure function has no side effects, so a pure function without a return value is meaningless, something like
f :: Int -> ()
f x = let y = x * x + 3 in ()
won't do any computation, y is never calculated and all inputs you give will return the same value. However, if you have an impure function, such as one that writes a file or prints something to the screen then it must exist in a monadic context. If you don't understand monads yet, don't worry. They take a bit to get used to, but they're a very powerful and useful abstraction that can make a lot of problems easier. A monad is something like IO, and in Haskell this takes a type parameter to indicate the value that can be stored inside this context. So you can have something like
putStrLn :: String -> IO ()
Or
-- FYI: FilePath is an alias for String
writeFile :: FilePath -> String -> IO ()
these have side effects, denoted by the return value of IO something, and the () something means that there is no meaningful result from that operation. In Python 3, for example, the print function returns None because there isn't anything meaningful to return after printing a value to the screen. The () can also mean that a monadic context has a meaningful value, such as in readFile or getLine:
getLine :: IO String
readFile :: FilePath -> IO String
When writing your main function, you could do something like
main = do
putStrLn "Enter a filename:"
fname <- getLine -- fname has type String
writeFile fname "This text will be in a file"
contents <- readFile fname
putStrLn "I wrote the following text to the file:"
putStrLn contents
FP says function should have single resresponsibility, then how do we handle log statements inside the method? That doesn't violate the rule?
Most functions don't need logging inside them. I know that sounds weird, but it's true. In Haskell and most other functional languages, you'll write a lot of small, easily testable functions that each do one step. It's very common to have lots of 1 or 2 line functions in your application.
When you actually do need to do logging, say you're building a web server, there are a couple different approaches you can take. There is actually a monad out there called Writer that lets you aggregate values as you perform operations. These operations don't have to be impure and do IO, they can be entirely pure. However, a true logging framework that one might use for a web server or large application would likely come with its own framework. This is so that you can set up logging to the screen, to files, network locations, email, and more. This monad will wrap the IO monad so that it can perform these side effects. A more advanced one would probably use some more advanced libraries like monad transformers or extensible effects. These let you "combine" different monads together so you can use utilities for both at the same time. You might see code like
type MyApp a = LogT IO a
-- log :: Monad m => LogLevel -> String -> LogT m ()
getConnection :: Socket -> MyApp Connection
getConnection sock = do
log DEBUG "Waiting for next connection"
conn <- liftIO $ acceptConnection sock
log INFO $ "Accepted connection from IP: " ++ show (connectionIP conn)
return conn
I'm not expecting you to understand this code fully, but I hope you can see that it has logging and network operations mixed together. The liftIO function is a common one with monad transformers that "transforms" an IO operation into a new monad that wraps IO.
This may sound pretty confusing, and it can be at first if you're used to Python, Java, or C++ like languages. I certainly was! But after I got used to thinking about problems in this different way makes me wish I had these constructs in OOP languages all the time.
I can answer from Haskell perspective.
FP says function should take one input and gives single output. So what should I do with void methods? It doesn't return anything right?
Because that's what actually functions are! In mathematics, every functions takes some input and gives you some output. You cannot expect some output without giving any input. void methods you see in other languages doesn't make sense in a mathematical way. But in reality void methods in other languages do some kind of IO operations, which is abstracted as IO monad in Haskell.
how do we handle log statements inside the method
You can use a monad transformer stack and lift your IO log operations to perform there. In fact, writer monad can do log operations purely without any IO activities.

How to avoid creating an orphan FromJSON instance for Data.Tree

I'm using the aeson package. I have a datatype which uses Data.Tree in its declaration. Like the following, only more complex:
data Foo = Foo {
bat :: Text
, xux :: Maybe Text
, tri :: Tree Text
}
I want to use Data.Aeson.TH to generate a FromJSON instance for this type.
$(deriveJSON defaultOptions ''Foo)
But Data.Tree does not have a standard instance for FromJSON, meaning that I would need to declare an orphan instace.
Is there some way to avoid creating that orphan instance, while still being able to use deriveJSON?
In order for an instance to be canonical (i.e. not an orphan), it needs to be defined in the same module as either the type constructor (Data.Tree) or the class declaration (Data.Aeson.Types). So the only way to define a non-orphan instance would be to fork aeson (since aeson depends on containers).
I'd recommend filing a ticket with aeson, or possibly a pull request, to get it added upstream. Until then, if you don't plan to distribute the code, defining an orphan instance shouldn't cause much trouble. If you're working on code you want to publish, the safest solution is to create a newtype wrapper around Tree, then make a FromJSON instance for the newtype.

Haskell Programmatically/Dynamically Define Functions

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.