Syntax What does $$ mean in Haskell? - haskell

"Ugh," you might think... "Another syntax question, here let me google that for you noob." But alas! I have googled it, and I am still stumped!
Found in this code from the yesod blog
import System.IO
import Data.Enumerator
import Data.Enumerator.Binary
main =
withFile "output.txt" WriteMode $ \output ->
run_ $ enumFile "input.txt" $$ iterHandle output
However the "$$" operator is new to me. The Haskell 2010 report only mentions it once as an operator symbol. What does it do?

In Haskell, operators like $$ are not part of the syntax, they are user-definable functions. Hence, you need to look up the API documenation for Yesod to see what $$ is. In particular, the function $$ from your example is documented here.

There's Hoogle, which is pretty good but unfortunately doesn't know many packages.
Hayoo knows much more, but its interface seems quirky, and it doesn't seem to offer a command-line tool like hoogle does.
If you have an idea what package you're dealing with, you can directly go to its documentation—e.g. the docs of the enumerator package, with the module list at the bottom. Also, these docs always have an index, and let you view the source code via the source links.
As a last resort, use cabal unpack enumerator and grep through the code.

Just use hoogle and be sure to tell it what packages you are using - it works fine.
http://haskell.org/hoogle/?hoogle=%28%24%24%29+%2Benumerator

Related

Embedding a domain specific language in an OCaml toplevel -- to Camlp4 or not?

I have some code that includes a menhir-based parser for a domain specific language (a logic). For the sake of my sanity while debugging, it would be great to be able to type instances of this language (formulas) directly in the toplevel like so:
# f = << P(x,y) & x!=y >>
Is campl4/5 my only option? If yes, I find the documentation rather intimidating. Is there an example/tutorial that is close-enough to my use case and that I could conceivably adapt? (For instance, syntax extensions that introduce new keywords do not seem relevant). Thanks!
If you're willing to call a function to do the parsing, you can use ocamlmktop to include your parser into the top level. Then you can install printers for your types using #install_printer. The sessions might look like this then:
# let x = parse ()
<< type your expression here >>
# x : type = <<formatted version>>
I have used specialed printers, and they definitely help a lot with complicated types. I've never gotten around to using ocamlmktop. I always just load in my code with #load and #use.
This is a lot easier than mastering camlp4/5 (IMHO). But maybe it's a bit too crude.
Yes, you can use camlp4 and it will work reasonably well (including in the toplevel), but no, it's not well-documented, and you will have to cope with that.
For an example that is close to your use-case, see the Lambda calculus quotation example of the Camlp4 wiki.
For the toplevel, it will work easily. You can dynamically load "camlp4o.cmo" then your syntactic extension in the toplevel, or use findlib which handles that: from the toplevel, #use "topfind";;, then #camlp4o;;, then #require "myfoo.syntax";; where myfoo.syntax is the name of the findlib package you've created to deploy your extension.

System.Directory.getDirectoryContents unicode support

The following code prints something like °Ð½Ð´Ð¸Ñ-ÐÑпаниÑ
getDirectoryContents "path/to/directory/that/contains/files/with/nonASCII/names"
>>= mapM_ putStrLn
Looks like it is a ghc bug and it is fixed already in repository. But what to do until everybody upgrade ghc?
The last time I encountered such the problem (it was few years ago, btw), I used utf8-string package to convert strings, but I don't remember how I did it, and ghc unicode support was changed visibly last years.
So, what is the best (or at least working) way to get directory contents with full unicode support?
ghc version 7.0.4
locale en_US.UTF-8
Here's a simple workaround using decodeString and encodeString from utf8-string.
import System.Directory
import qualified Codec.Binary.UTF8.String as UTF8
main = do
getDirectoryContents "." >>= mapM_ (putStrLn . UTF8.decodeString)
putStrLn "------------"
readFile (UTF8.encodeString "brøken-file-nåme.txt") >>= putStrLn
Output:
.
..
brøken-file-nåme.txt
Broken.hs
------------
hello
I would recommend looking at system-filepath, which provides an abstract datatype for representing filepaths. I've used it extensively for some internal code and it works wonderfully.

What is the least verbose way to convert a Double to Data.Text?

How do I convert a Double to Data.Text?
In essence, I had the following code:
Data.Text.pack $ show 9.0
That code has some rather obvious silliness. So I dug around in the documentation and came up with this:
toStrict $ toLazyText $ realFloat 9.0
This seems better, but it seems like there should be a more direct method, but I can't find anything with type Double -> Data.Text. Is this the best way? It seems that if I switch to lazy Text I can avoid this, but I'm not quite ready to do that.
Any words of wisdom?
You can use the printf like package text-format.
ClassyPrelude provides a Show typeclass as mentioned in Thomas' previous answer.
See tshow and tlshow. The latter one produces a lazy text.
Note that the default implementation is just T.fromList . Prelude.show.
I recommend reading the Yesod blog on ClassyPrelude for general information about that package. Note that it is not a drop-in replacement for the standard prelude.
The tongue-in-cheek answer:
f :: Double -> Data.Text
f = Data.Text.pack . show
Then you simply use
f 9.0
Can't get much more terse than that, right? Don't be afraid to roll your own utility methods for convenience (though they should probably have more descriptive names than f). If you think it could be generally useful, then contact the maintainer.

How do I rotate a JPEG image by 45° and save it back to disk in Haskell?

How do I rotate a JPEG image by 45° and save it back to disk?
As far as I know, there is no good image manipulation library for Haskell yet.
Better way
You can use hsmagick (bindings to libmagick) to manipulate images.
See TomMD's answer for an example.
Easy way
But if you want to do it from Haskell, this can do the trick (assuming that ImageMagick is available):
import System.Cmd (system)
import System.Environment (getArgs)
main = do
(original:rotated:_) <- getArgs
system $ "convert -rotate \"-45\" \"" ++ original ++ "\" \"" ++ rotated ++ "\""
Usage:
runghc rotate.hs original.jpg rotated45.jpg
Hard way
Or you can choose the hard way, and implement rotation algorithm yourself. To read and write almost all image formats in Haskell, you can use Codec.Image.DevIL library. If you do it, it would be kind of you to put this code on Hackage.
The GD library lets you do this, but the Haskell bindings ( http://hackage.haskell.org/package/gd ) don't include the appropriate function at the moment. One also could either make a feature request to the maintainer, or simply patch it and send it upstream. The Graphics.GD.Internal module (not exported) in fact already has a commented out binding to the appropriate function ( http://hackage.haskell.org/packages/archive/gd/3000.5.0/doc/html/src/Graphics-GD-Internal.html ), so it should be very simple, I imagine, to finish the job (and I'm sure, the work will be appreciated).
Look around on Hackage. I know Tim started working on bindings to libmagick, which wasn't enough to stop me from dropping down to generating script-fu for GIMP when I needed image manipulation, but it's enough for you if you're just doing simple things like rotation:
liftM (rotateImage 45) (readImage file) >>= writeImage file2
I see Cale also has an ImLib that appears more feature complete:
loadImageImmediately file >>= contextSetImage >>
createRotatedImage 45 >>= contextSetImage >> saveImage file2
As I said, look around and let us know!

Need a tutorial for using GHC to parse and typecheck Haskell

I'm working on a project for analyzing Haskell code. I decided to use GHC to parse the source and infer types rather than write my own code to do that. Right now, I'm slogging through the Haddock docs, but it's slow going. Does anyone know of a good tutorial?
EDIT: To clarify, I'm not looking for something like hlint. I'm writing my own tool to analyze the runtime characteristics of Haskell code, so it's like I'm writing a different hlint. What I'm looking for is basically an expansion of the wiki page GHC As a library.
Ah! found a much better entry point into the docs at:
http://www.haskell.org/ghc/docs/latest/html/libraries/ghc-6.12.1/GHC.html
I updated the wikipage with this example:
Here we demonstrate calling parseModule, typecheckModule, desugarModule, getNamesInScope, and getModuleGraph. This works for haskell-platform, ghc-6.12.1.
bugs: libdir is hardcoded. See ghc-paths above.
--A.hs
--invoke: ghci -package ghc A.hs
import GHC
import Outputable
--import GHC.Paths ( libdir )
import DynFlags ( defaultDynFlags )
libdir = "/usr/local/lib/ghc-6.12.1"
targetFile = "B.hs"
main = do
res <- example
print $ showSDoc ( ppr res )
example =
defaultErrorHandler defaultDynFlags $ do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
setSessionDynFlags dflags
target <- guessTarget targetFile Nothing
setTargets [target]
load LoadAllTargets
modSum <- getModSummary $ mkModuleName "B"
p <- parseModule modSum
t <- typecheckModule p
d <- desugarModule t
l <- loadModule d
n <- getNamesInScope
c <- return $ coreModule d
g <- getModuleGraph
mapM showModule g
return $ (parsedSource d,"/n-----/n", typecheckedSource d)
--B.hs
module B where
main = print "Hello, World!"
Adam, this is pretty tough sledding. Ever since its launch in 2006, the GHC API has been somewhat underdocumented. What I would recommend is to try to find some small applications that have been written using the GHC API. The right place to ask is probably the GHC users' mailing list.
One such program is ghctags, which ships with the GHC source tree. I wrote the original version, but I can't recommend it—there are so many footprints on the code that I can no longer follow it. The best I can say is that although it's hard to follow, it's at least small and hard to follow—much simpler than all of GHC.
If parsing is the most important thing, I recommend haskell-src-exts. It parses all of Haskell98, a whole pile of extensions and is very easy to use.
The Haskell wiki and GHC documentation probably has what you are looking for if you search for the articles. Also a tool you might be interested in is hlint, for checking the syntax and other things about your source code.

Resources