I'm taking input from stdin() and splitting it into a Vec<char>
For some reason there are 2 elements at the end of my vector. Can anyone tell me why they are there and how to get rid of them?
This is where I split the input into a Vec<char>:
// Splits regEx into vector of chars
let mut reg_ex: Vec<char> = input.chars().collect();
This is the code iterating through the Vec:
let mut i = 0;
for character in ®_ex {
println!("{} {}", i, character);
i = i + 1;
}
And this is the output I get with 2 extra elements at the end:
User input required:
aaa
0 a
1 a
2 a
3
4
Assuming you are on Windows these are likely the newline characters \r\n.
You can get rid of them by calling .trim_end() on input. Note that this would also strip any whitespace at the end of your line, if you wanted to keep that.
Related
New to Julia, trying to simply ask the user to choose 5 numbers and put it into an array and print the array. My output only says pick 5 numbers with "nothing" followed underneath. I cant seem to figure out why it wont read my inputs.
function ask()
lst = []
i = 0
println("pick 5 numbers to add to a list")
while i < 5
choice = readline
choice = push!(lst, choice);
i += 1
end
end
println(ask())
You were assigning function reference to list elements rather than calling the function.
This should be:
function ask()
lst = String[]
i = 0
println("pick 5 numbers to add to a list")
while i < 5
choice = readline()
choice = push!(lst, choice);
i += 1
end
lst
end
If you want numbers rather than Strings the last line could be parse.(Int, lst) or you could add this conversion near readline
Note that if you do not plan to introduce some error checking etc. this all code could be simply written as:
println("pick 5 numbers to add to a list")
lst = [parse(Int, readline()) for _ in 1:5]
I am new to Elixir language and I am having some issues while writing a piece of code.
What I am given is a 2D array like
list1 = [
[1 ,2,3,4,"nil"],
[6,7,8,9,10,],
[11,"nil",13,"nil",15],
[16,17,"nil",19,20] ]
Now, what I've to do is to get all the elements that have values between 10 and 20, so what I'm doing is:
final_list = []
Enum.each(list1, fn row ->
Enum.each(row, &(if (&1 >= 10 and &1 <= 99) do final_list = final_list ++ &1 end))
end
)
Doing this, I'm expecting that I'll get my list of numbers in final_list but I'm getting blank final list with a warning like:
warning: variable "final_list" is unused (there is a variable with the same name in the context, use the pin operator (^) to match on it or prefix this variable with underscore if it is not meant to be used)
iex:5
:ok
and upon printing final_list, it is not updated.
When I try to check whether my code is working properly or not, using IO.puts as:
iex(5)> Enum.each(list1, fn row -> ...(5)> Enum.each(row, &(if (&1 >= 10 and &1 <= 99) do IO.puts(final_list ++ &1) end))
...(5)> end
...(5)> )
The Output is:
10
11
13
15
16
17
19
20
:ok
What could I possibly be doing wrong here? Shouldn't it add the elements to the final_list?
If this is wrong ( probably it is), what should be the possible solution to this?
Any kind of help will be appreciated.
As mentioned in Adam's comments, this is a FAQ and the important thing is the message "warning: variable "final_list" is unused (there is a variable with the same name in the context, use the pin operator (^) to match on it or prefix this variable with underscore if it is not meant to be used)" This message actually indicates a very serious problem.
It tells you that the assignment "final_list = final_list ++ &1" is useless since it just creates a local variable, hiding the external one. Elixir variables are not mutable so you need to reorganize seriously your code.
The simplest way is
final_list =
for sublist <- list1,
n <- sublist,
is_number(n),
n in 10..20,
do: n
Note that every time you write final_list = ..., you actually declare a new variable with the same name, so the final_list you declared inside your anonymous function is not the final_list outside the anonymous function.
I want to find the longest word in a string vector. Using APL I know that the shape function will return the length of a string e.g.
⍴ 'string' ⍝ returns 6
The reduce function allows me to map diadic functions along a vector but since shape is monadic this will not work. How can I map the shape function in this case? For example:
If the vector is defined as:
lst ← 'this is a string'
I want to do this:
⍴'this' ⍴'is' ⍴'a' ⍴'string'
The "typical" approach would be to treat it as a segmented (or: separated) string and prefix it with the separator (a blank) and pass it to a dfn for further analysis:
{}' ',lst
The fn then looks for the separator and uses it to build the vectors of words:
{(⍵=' ')⊂⍵}' ',lst
┌─────┬───┬──┬───────┐
│ this│ is│ a│ string│
└─────┴───┴──┴───────┘
Let's remove the blanks:
{1↓¨(⍵=' ')⊂⍵}' ',lst
┌────┬──┬─┬──────┐
│this│is│a│string│
└────┴──┴─┴──────┘
And then you "just" need to compute the length of each vector:
{1↓¨(⍵=' ')⊂⍵}' ',lst
This is a direct implementation of your request. However, if you're not interested in the substrings themselves but only the length of "non-blank segments", a more "APLy"-solution might be to work with booleans (usually most efficient):
lst=' '
0 0 0 0 1 0 0 1 0 1 0 0 0 0 0 0
So the ones are the positions of the separators - where do they occur?
⍸lst=' '
5 8 10
But we need a trailing blank, too - otherwise we're missing the end of text:
⍸' '=lst,' '
5 8 10 17
So these (minus the positions of the preceeding blank) should give the length of the segments:
{¯1+⍵-0,¯1↓⍵}⍸' '=lst,' '
4 2 1 6
This is still somewhat naive and can be expressed in more advanced way - I leave that as an "exercise for the reader" ;-)
While MBaas has already thoroughly answered, I thought it might be interesting to learn the idiomatic Dyalog "train" ≠⊆⊢ derived from Paul Mansour's comment. It forms a dyadic function which splits its right argument on occurrences of the left argument:
Split ← ≠⊆⊢
' ' Split 'this is a string'
┌────┬──┬─┬──────┐
│this│is│a│string│
└────┴──┴─┴──────┘
You can extend this function train to do the whole job:
SegmentLengths ← ≢¨Split
' ' SegmentLengths 'this is a string'
4 2 1 6
Or even combine the definitions in one go:
SegmentLengths ← ≢¨≠⊆⊢
' ' SegmentLengths 'this is a string'
4 2 1 6
If you are used to the idiomatic expression ≠⊆⊢ then it may actually read clearer than any well-fitting name you can give for the function, so you might as well just use the expression in-line:
' ' (≢¨≠⊆⊢) 'this is a string'
4 2 1 6
For how to find the longhest word in a string i would use, in NARS APL the function
f←{v/⍨k=⌈/k←≢¨v←(⍵≠' ')⊂⍵}
example to use
f 'this is a string thesam'
string thesam
explenation
{v/⍨k=⌈/k←≢¨v←(⍵≠' ')⊂⍵}
v←(⍵≠' ')⊂⍵ split the string where are the spaces and assign result to v
k←≢¨v to each element of v find the lenght, the result will be a vector
that has same lenght of v saved in k
⌈/k this find max in k
k= and this for each element of k return 0 if it is not max, 1 if it is max
v/⍨ this return the element of v that are max
I have a mixed vector of floats and characters that I'm streaming from a text file. This vector is being read in as a string. My problem is that I want to parse only the floats and ignore the characters. How can I do this?
v = "Float_or_Char"
if isblank(v) == false # <-- v might be blank as well
Parse(Float64,v) # <-- only if v is a Float (how do I do this?)
end
Supposing x is a vector of strings, some of which are floats-as-strings and the rest are actual strings, you could do something like
for i in 1:length(x)
f = NaN
try
f = float(x[i])
println("$i is a float")
catch
println("$i isn't a float")
end
end
If you are using Julia 0.4 (not yet released), you could get really fancy if you just wanted the floats from x using the new Nullable type and the new method tryparse
maybe_floats = map(s->tryparse(Float64,s), x)
floats = map(get, filter(n->!isnull(n), maybe_floats))
I would think that the following Rebol 3 code:
x: [newline 1 2]
y: [
1 2]
print x
print new-line? x
print y
print new-line? y
should output:
<empty line>
1 2
true
<empty line>
1 2
true
but what is output is:
<empty line>
1 2
false
1 2
true
Both blocks, when reduced, should yield a newline character followed by '1' and '2' and so, IMO, should print identically. Less clear is whether new-line? on the two blocks should also give the same result since the newline keyword should be equivalent to the literal newline for this kind of test.
The flag which is checked by new-line? and set by new-line is used only by LOAD and MOLD. For all other semantic purposes in the program, it might as well not be there.
Therefore your x and y are completely different. Note that:
x: [newline 1 2]
y: [
1 2]
3 = length? x
2 = length? y
It's a quirk of Rebol that it singles out this one bit of whitespace information to stow in a hidden place. But arguably the choice to break a line represents something that is often significant in source, that if you reflect it back out into text you'd like to preserve more than the rest of the whitespace.
Let's start with NEWLINE: newline is a word bound to a char! value:
>> ? newline
NEWLINE is a char of value: #"^/"
That's Rebol's escape sequence for Unicode codepoint U+000A, commonly used as line feed ("LF") control code.
So your first example code [newline 1 2] has nothing to do with the NEW-LINE function. It simply describes a block containing three values: newline (a word!), 2 (an integer!), and 3 (another integer!). If you REDUCE the block from your first example, you'll get another block of three values: char!, integer!, and integer!:
>> reduce [newline 1 2]
== [#"^/" 1 2]
Now PRINT does not only REDUCE, it does REFORM (first REDUCE, then FORM) a block argument. FORM of a block converts the elements to a string representation and then joins those with spaces in between:
>> form [1 2 3]
== "1 2 3"
Putting those pieces together we finally know how to arrive at the output you are seeing for your first example:
>> basis: [newline 1 2 3]
== [newline 1 2 3]
>> step1: reduce basis
== [#"^/" 1 2 3]
>> step2: form step1
== "^/1 2 3"
>> print step2
1 2 3
So the question remains, why does the second example not print identically?
That's because FORM (used by PRINT, as described above) does not respect the NEW-LINE flag when converting from a block to a string.
This flag is "meta-data", not unlike e.g. the index position of an element within a block. So just as you don't have elements at index positions 8 and 6 just because you write a block like [8 6], you don't set the new-line flag for a position just because you happen to put an element there which is a character that on some systems represents a line break: [1 newline 2].
And this finally brings us to the last part of the puzzle: NEW-LINE? does not check if a given string represents a line break. It checks if a block (at its current position) has the new-line flag set.