I'am new to the Julia language and below is a code that I encode using the Jupyter Notebook, but there is no output but when i tried the same code using the REPL, there is an output. Please help me with this.
NOTE: the value of the variable is set to either 'S' or 's' and the input is a function that i copied from Ismael Venegas Castelló (Julia request user input from script). Thank you by the way Mr. Castelló.
if choose == 'S' || choose == 's'
str = input("Please input a String.");
che = input("please input a character to be search");
search(str, che);
end
Worked totally fine for me this way in JuliaPro(0.5.1.1).
julia> choose='s'
's'
julia> function input(prompt::AbstractString="")
print(prompt)
return chomp(readline())
end
input (generic function with 2 methods)
julia> if choose == 'S' || choose == 's'
str = input("Please input a String.");
che = input("please input a character to be search");
search(str, che);
end
Please input a String.It is working.
please input a character to be searchk
10:10
Related
I'm new to F#, apologies if I'm missing something obvious here.
I have the following code, with the intent to get user input and convert it to a uint:
let println ln =
printfn "%s" ln
let rec getUserKeyInput =
let x = System.Console.ReadKey()
string x
let getInputWithPrompt prompt =
println prompt
getUserKeyInput
let rec getUserUIntFromStr str =
try
let i = str |> uint
i
with
| :? System.FormatException -> println "Please enter a positive integer";
(getUserUIntFromStr (getUserKeyInput))
When getUserUIntFromStr is called with let i = getUserUIntFromStr str "Please enter a positive integer" is printed infinitely. I've also tried Console.ReadLine() and stdin.ReadLine(), both in interactive and from main, with the same results. It looks to me like none of the "Read" functions are waiting for input, but that doesn't seem right and I'm guessing I've done something wrong. Any suggestions?
getUserKeyInput is a value, not a function. It's evaluated only once at init time, not every time you reference it.
To make it a function, you need to give it a parameter. What type of parameter? Well, technically any type will do, but F# has you covered: for situations where you need to have some value, but there isn't a sensible value to use (which happens surprisingly often), there is a special type unit with a single value denoted as parentheses ():
let getUserKeyInput () =
let x = System.Console.ReadKey()
string x
(also note that rec is unnecessary, because the function isn't actually recursive)
(also note that ReadKey takes such parameter as well - it's the same deal there)
And then pass the parameter to call the function:
println "Please enter a positive integer"
getUserUIntFromStr (getUserKeyInput ())
I have this code for returning a string in all lower case, using recursion:
function min(ch:string):string;
begin
if ( ch = '' ) then
min:= ''
else
if (ch[1] in ['A'..'Z']) then
begin
ch[1]:=chr(ord(ch[1])+32);
min:= ch[1] + min(copy(ch,2,length(ch)-1));
end;
end;
But it doesn't work:
When I run it with the example min('AbC') the output is a only not abc.
Where is the problem here?
The problem is that you do not always call the recursive function. As soon as you find a letter that is already lower case, you don't look any more at the characters that follow it. And so the return value is truncated up to that character.
You should also call it when the character being looked at is not a capital letter. So move the recursive call out of that if, and it will work:
function min(ch:string):string;
begin
if ( ch = '' ) then
min:= ''
else
begin
if (ch[1] in ['A'..'Z']) then
ch[1]:=chr(ord(ch[1])+32);
min:= ch[1] + min(copy(ch,2,length(ch)-1));
end;
end;
See it run on ideone.com.
When I run this script, it asks for the input. But then, it ends on the pause and doesn't prints anything. Some solution?
PS:This is Python 3.4.1
variable = input('What do you want to be?: ')
if variable is 'a unicorn' :
print ('You are now a unicorn!')
elif variable is 'a pig' :
print ('You are now a pig!')
pause = input #This is here just to pause the script
first of all you need to know the difference between is and ==
== is for value equality. Use it when you would like to know if two objects have the same value.
is is for reference equality. Use it when you would like to know if two references refer to the same object.
>>> variable = 'a unicorn'
>>> variable is 'a unicorn'
False
>>> variable == 'a unicorn'
True
just replace is with ==
How do I request user input from a running script in Julia? In MATLAB, I would do:
result = input(prompt)
Thanks
The easiest thing to do is readline(stdin). Is that what you're looking for?
I like to define it like this:
julia> #doc """
input(prompt::AbstractString="")::String
Read a string from STDIN. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
""" ->
function input(prompt::AbstractString="")::String
print(prompt)
return chomp(readline())
end
input (generic function with 2 methods)
julia> x = parse(Int, input());
42
julia> typeof(ans)
Int64
julia> name = input("What is your name? ");
What is your name? Ismael
julia> typeof(name)
String
help?> input
search: input
input(prompt::AbstractString="")::String
Read a string from STDIN. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a trailing newline before reading input.
julia>
A function that checks that the answer provided matches the expected Type:
Function definition:
function getUserInput(T=String,msg="")
print("$msg ")
if T == String
return readline()
else
try
return parse(T,readline())
catch
println("Sorry, I could not interpret your answer. Please try again")
getUserInput(T,msg)
end
end
end
Function call (usage):
sentence = getUserInput(String,"Write a sentence:");
n = getUserInput(Int64,"Write a number:");
Now in Julia 1.6.1, it's as simple as typing:
num = readline()
Yea! without any arguments since the default value for the IO positional argument of the readline() function is "stdin". So in the above example Julia will read the input from the user and store it in the variable "num".
First I ran
Pkg.add("Dates")
then
using Dates
println()
print("enter year "); year = int(readline(STDIN))
print("enter month "); month = int(readline(STDIN))
print("enter day "); day = int(readline(STDIN))
date = Date(year, month, day)
println(date)
So I work with files, and I need to know the largest line in file X. Using Unix awk results in a Int that I'm looking for. But in Haskell how can I return that value and save it to a variable?
I tried define something with IO [Int] -> [Int]
maxline = do{system "awk ' { if ( length > x ) { x = length } }END{ print x }' filename";}
doesn't work cause:
Couldn't match expected type 'Int',against inferred type 'IO GHC.IO.Exception.ExitCode'
This is because the system action returns the exit status of the command you run which cannot be converted to Int. You should use the readProcess to get the commands output.
> readProcess "date" [] []
"Thu Feb 7 10:03:39 PST 2008\n"
Note that readProcess does not pass the command to the system shell: it runs it directly. The second parameter is where the command's arguments should go. So your example should be
readProcess "awk" [" { if ( length > x ) { x = length } }END{ print x }", "/home/basic/Desktop/li11112mp/textv"] ""
You can use readProcess to get another program's output. You will not be able to convert the resulting IO String into a pure String; however, you can lift functions that expect Strings into functions that expect IO Strings. My two favorite references for mucking about with IO (and various other monads) are sigfpe's excellent blog posts, You Could Have Invented Monads! (And Maybe You Already Have.) and The IO Monad for People who Simply Don't Care.
For this particular problem, I would strongly suggest looking into finding a pure-Haskell solution (that is, not calling out to awk). You might like readFile, lines, and maximumBy.