I want to create an operator .f. that checks whether a file exists so that I can write
if (.f. filename) Then ...
I have already written a function to do this, now have to create the interface. What would the constraints on e function arguments for having the mentioned functionality?
You can use the inquire intrinsic:
module fileIO
interface operator( .f. )
module procedure file_exists
end interface
contains
function file_exists(filename) result(res)
implicit none
character(len=*),intent(in) :: filename
logical :: res
! Check if the file exists
inquire( file=trim(filename), exist=res )
end function
end module
program test
use fileIO
print *, file_exists('/dev/null')
print *, .f. '/dev/null'
end program
Related
In Standard ML, I have opened a file using TextIO.openIn "myfile.txt". This returns a value of type TextIO.instream. How do I get the POSIX file descriptor of type Posix.FileSys.file_desc from this instream?
Here's a function which does it, returning a Posix.FileSys.file_desc option.
fun instreamToPosixFD (ins: TextIO.instream) : Posix.FileSys.file_desc option =
let
val (TextPrimIO.RD reader, _) =
TextIO.StreamIO.getReader (TextIO.getInstream ins)
in
case #ioDesc reader of
NONE => NONE
| SOME id => Posix.FileSys.iodToFD id
end
The use of option for the output is consistent with the types in the Basis Library. As far as I can tell, if you open a file with TextIO.openIn and pass the result to this function, you will get a SOME result. My guess is that NONE is only possible for a TextIO.instream that is not backed by an open file.
I want to create an operator .f. that checks whether a file exists so that I can write
if (.f. filename) Then ...
I have already written a function to do this, now have to create the interface. What would the constraints on e function arguments for having the mentioned functionality?
You can use the inquire intrinsic:
module fileIO
interface operator( .f. )
module procedure file_exists
end interface
contains
function file_exists(filename) result(res)
implicit none
character(len=*),intent(in) :: filename
logical :: res
! Check if the file exists
inquire( file=trim(filename), exist=res )
end function
end module
program test
use fileIO
print *, file_exists('/dev/null')
print *, .f. '/dev/null'
end program
Here is some invalid HStringTemplate syntax:
option_a = $options.a$
option_b = $options.b$
$if options.option_c_is_needed$
option_c = $option.c$
$end$
In other words, part of template file should be created only if specific predicate is true. How can it be achieved via HStringTemplate? If there is no way to do that in it, what libraries could be helpful here?
May be there is some analog of erubis mechanism with ability to use haskell code inside template files?
Hammar's comment is correct. See below:
*Main Text.StringTemplate> render $ setAttribute "optSet" False $ (newSTMP "OptSet: $if(optSet)$Option Is Set$else$Option Isn't Set$endif$" :: StringTemplate String)
"OptSet: Option Isn't Set"
*Main Text.StringTemplate> render $ setAttribute "optSet" True $ (newSTMP "OptSet: $if(optSet)$Option Is Set$else$Option Isn't Set$endif$" :: StringTemplate String)
"OptSet: Option Is Set"
I'm writing a C++ application that needs to interpret and evaluate haskell code. This code isn't known at compile time but given by the user.
Is there a way to use a haskell compiler/interpreter (like GHCi or hugs) as a library?
I found FFI but this seems only to work for haskell code that is known at compile time.
I found the GHC API and hint, but they seem only to work when I want to interpret haskell code from out of haskell.
Instead of using the GHC api I would suggest binding to Hint for this particular approach, which is just a simplified wrapper around the GHC api. The reason I would recommend this is because the GHC api has a bit of a steep learning curve.
But anyway, Like I said In my comment, depending on how deep you want this to go it would require surprisingly few FFI calls. Below I give an example on how to run expressions from a loaded file and return the results (only if there's a show instance). This is just the basics, returning the results as a structure should be possible too.
module FFIInterpreter where
import Language.Haskell.Interpreter
import Data.IORef
import Foreign.StablePtr
type Session = Interpreter ()
type Context = StablePtr (IORef Session)
-- ## Export
-- | Create a new empty Context to be used when calling any functions inside
-- this class.
-- .
-- String: The path to the module to load or the module name
createContext :: ModuleName -> IO Context
createContext name
= do let session = newModule name
_ <- runInterpreter session
liftIO $ newStablePtr =<< newIORef session
newModule :: ModuleName -> Session
newModule name = loadModules [name] >> setTopLevelModules [name]
-- ## Export
-- | free a context up
freeContext :: Context -> IO ()
freeContext = freeStablePtr
-- ## Export = evalExpression
runExpr :: Context -> String -> IO String
runExpr env input
= do env_value <- deRefStablePtr env
tcs_value <- readIORef env_value
result <- runInterpreter (tcs_value >> eval input)
return $ either show id result
Since we have to exit haskell land we have to have some way to refer to the Context, We can do this with a StablePtr and I just wrap it in an IORef to make it mutable in case you want to change things in the future. Note that the GHC API does not support type checking an in-memory buffer, so you have to save the code you want to interpret to a temporary file before loading it.
The -- ## Annotations are for my tool Hs2lib, don't mind them if you don't use it.
My test file is
module Test where
import Control.Monad
import Control.Monad.Instances
-- | This function calculates the value \x->x*x
bar :: Int -> Int
bar = join (*)
and we can test this using a simple test
*FFIInterpreter> session <- createContext "Test"
*FFIInterpreter> runExpr session "bar 5"
"25"
So yeah, it works in Haskell, now to make it work outside of haskell.
Just add to the top of the file a few instructions for Hs2lib on how to marshal ModuleName because that type is defined in a file which it doesn't have the source to.
{- ## INSTANCE ModuleName 0 ## -}
{- ## HS2HS ModuleName CWString ## -}
{- ## IMPORT "Data.IORef" ## -}
{- ## IMPORT "Language.Haskell.Interpreter" ## -}
{- ## HS2C ModuleName "wchar_t*#4" ## -}
or
{- ## HS2C ModuleName "wchar_t*#8" ## -}
if on a 64bit architecture,
and Just invoke Hs2lib
PS Haskell\FFIInterpreter> hs2lib .\FFIInterpreter.hs -n "HsInterpreter"
Linking main.exe ...
Done.
And you'll end up with among others, an Include file with
#ifdef __cplusplus
extern "C" {
#endif
// Runtime control methods
// HsStart :: IO ()
extern CALLTYPE(void) HsStart ( void );
// HsEnd :: IO ()
extern CALLTYPE(void) HsEnd ( void );
// createContext :: ModuleName -> IO (StablePtr (IORef (Interpreter ())))
//
// Create a new empty Context to be used when calling any functionsinside this class.
// String: The path to the module to load or themodule name
//
extern CALLTYPE(void*) createContext (wchar_t* arg1);
// freeContext :: StablePtr (IORef (Interpreter ())) -> IO ()
//
// free a context up
//
extern CALLTYPE(void) freeContext (void* arg1);
// evalExpression :: StablePtr (IORef (Interpreter ())) -> String -> IO String
extern CALLTYPE(wchar_t*) evalExpression (void* arg1, wchar_t* arg2);
#ifdef __cplusplus
}
#endif
I haven't tested the C++ side, but there's no reason it shouldn't work.
This is a very barebones example, if you compile it to a dynamic lib you probably want to redirect stdout, stderr and stdin.
Since GHC is written in Haskell, its API is exclusively available from Haskell. Writing the interfaces you need in Haskell and binding them to C with the FFI, as Daniel Wagner suggested, is going to be the simplest route. This is probably easier than using a direct binding of the GHC API to C would be; you get to use Haskell's strengths to build the interfaces you need, and only interface with them in C++ at the top layer.
Note that Haskell's FFI will only export to C; if you want a C++-ish wrapper around it, you'll have to write it as another layer.
(BTW, Hugs is ancient and unmaintained.)
I have been given the 3 functions below. Can anybody please help me to understand these? I am trying to port an application to C++ using Qt, but I don't understand these functions. So please help me!
Thanks in advance.
function 1:
def read_key
puts "read pemkey: \"#{#pkey}\"" if #verbose
File.open(#pkey, 'rb') do |io|
#key = OpenSSL::PKey::RSA.new(io)
end
end
function 2:
def generate_key
puts "generate pemkey to \"#{#pkey_o}\"" if #verbose
#key = OpenSSL::PKey::RSA.generate(KEY_SIZE)
# save key
File.open(#pkey_o, 'wb') do |file|
file << #key.export()
end
end
function 3:
def sign_zip
puts "sign zip" if #verbose
plain = nil
File.open(#zip, 'rb') do |file|
plain = file.read
end
#sig = #key.sign(OpenSSL::Digest::SHA1.new, plain)
end
There are probably two things about the above code that are confusing you, which if clarified, will help understand it.
First, #verbose and #key are instance variables, what a C++ programmer might call "member variables." The "if #verbose" following the puts statement literally means only do the puts if #verbose is true. #verbose never needs to be declared a bool--you just start using it. If it's never initialized, it's "nil" which evaluates to false.
Second, the do/end parts are code blocks. Many Ruby methods take a code block and execute it with a variable declared in those pipe characters. An example would be "array.each do |s| puts s; end" which might look like "for(int i = 0; i < array.size(); ++i) { s = array[i]; puts(s); }" in C++. For File.open, |io| is the file instance opened, and "read" is one of its methods.
These are all methods. #{#pkey_o} is string interpolation, substituting in the contents of an instance variable (called pkey_o; Ruby instance variables begin with # and class variables – unused here – begin with ##).
File.open(#pkey, 'rb') do |io|
#key = OpenSSL::PKey::RSA.new(io)
end
That opens the file whose name is stored in #pkey, stores the file handle in io (a block-local variable) and uses that with OpenSSL::PKey::RSA.new, whose result is stored in #key. Finally, it closes the file handle when the block is finished (at the end) whether or not it is a successful exit or an error case (in which case an exception would be thrown, but it would still be thrown). When translating this to C++, use of the RAII pattern is entirely reasonable (if you were going to Java, I'd say to use try/finally).