If file exists then continue [duplicate] - fortran

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

How do I get the file descriptor of a file opened using TextIO.openIn?

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.

Importing a specific function from a module

I have a module called prog1.py which contains a function and other statements, like this:
def func(a,b,c)
...
...
return output
var = input('input')
...
I'm trying to call just the function func from a different module prog2.py like this:
from prog1 import func
N = input('input2')
for i in range(N)
func(x,y,z) # with x,y,z already defined
So when executing prog2.py instead of asking for my input2, it asks for my input from prog1.py. I can move from prog1 import func to my for loop but I don't want it to ask for the other input. Is there a way to call func without using whatever else is in prog1.py?
The top level code of a module is executed upon import and there is no way around this.
If you don't want the line
var = input('input')
to be executed, remove it, put it in a function or guard it with
if __name__ == '__main__'
var = input('input')
(usually at the end of the module).

Operator to check file existence

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

Writing Haskell interpreter in C++ (using ghc or hugs as library)

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 am new to RUBY and i need to understand 3 functions

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).