I am trying to read an integer value from a simple text file.
Row in my input file looks like this:
1 4 15 43
2 4 12 33
... (many rows of 4 integers)
I have opened the file in the following way:
{ok, IoDev} = file:open("blah.txt",[read])
But only thing that I manage to read are bytes with all the functions available.
What I finally want to get from file are tuples of integers.
{1 4 15 43}
{2 4 12 33}
...
You must first use file:read_line/1 to read a line of text, and use re:split/2 to get a list of strings containing numbers. Then use the list_to_integer BIF to get integers.
Here's an example (surely there is a better solution):
#!/usr/bin/env escript
%% -*- erlang -*-
main([Filename]) ->
{ok, Device} = file:open(Filename, [read]),
read_integers(Device).
read_integers(Device) ->
case file:read_line(Device) of
eof ->
ok;
{ok, Line} ->
% Strip the trailing \n (ASCII 10)
StrNumbers = re:split(string:strip(Line, right, 10), "\s+", [notempty]),
[N1, N2, N3, N4] = lists:map(fun erlang:list_to_integer/1,
lists:map(fun erlang:binary_to_list/1,
StrNumbers)),
io:format("~w~n", [{N1, N2, N3, N4}]),
read_integers(Device)
end.
(EDIT)
I found a somewhat simpler solution that uses io:fread to read formatted input. It works well in your case but fails badly when the file is badly constructed.
#!/usr/bin/env escript
%% -*- erlang -*-
main([Filename]) ->
{ok, Device} = file:open(Filename, [read]),
io:format("~w~n", [read_integers(Device)]).
read_integers(Device) ->
read_integers(Device, []).
read_integers(Device, Acc) ->
case io:fread(Device, [], "~d~d~d~d") of
eof ->
lists:reverse(Acc);
{ok, [D1, D2, D3, D4]} ->
read_integers(Device, [{D1, D2, D3, D4} | Acc]);
{error, What} ->
io:format("io:fread error: ~w~n", [What]),
read_integers(Device, Acc)
end.
Haven't seen edited part
/*
You can try fread/3
read() ->
{ok, IoDev} = file:open("x", [read]),
read([], IoDev).
read(List, IoDev) ->
case io:fread(IoDev, "", "~d~d~d~d") of
{ok, [A,B,C,D]} ->
read([{A,B,C,D} | List], IoDev);
eof ->
lists:reverse(List);
{error, What} ->
failed
end.
*/
Related
Through PLY to achieve the "1+1 \n 2+2" result analysis, I think it is two irrelevant statements, but PLY has reduced them, how to make them irrelevant
def p_statement_expr(p):
'''statement : expression
print p[1]
def p_expr_num(p):
'''expression : NUMBER'''
p[0] = p[1]
if "__main__" == __name__:
parser = yacc.yacc(tabmodule="parser_main")
import time
t = time.time()
for i in range(1):
result = parser.parse("1+1 \n 2+2", debug=debug)
# print time.time() - t
# print result
Through PLY to achieve the "1+1 \n 2+2" result analysis, I think it is two irrelevant statements, but PLY has reduced them, how to make them irrelevant
PLY: PARSE DEBUG START State : 0 Stack : . LexToken(NUMBER,1,1,0) Action : Shift and goto state 3 State : 3 Stack : NUMBER . LexToken(ADD,'+',1,1) Action : Reduce rule [expression -> NUMBER] with [1] and goto state 5 Result : (1) State : 5 Stack : expression . LexToken(ADD,'+',1,1) Action : Shift and goto state 9 State : 9 Stack : expression ADD . LexToken(NUMBER,1,1,2) Action : Shift and goto state 3 State : 3 Stack : expression ADD NUMBER . LexToken(NUMBER,2,2,6) ERROR: Error : expression ADD NUMBER . LexToken(NUMBER,2,2,6)
When 2+2 is reported, how can I implement multi-line statement execution and automatically execute the following code after execution?
Ply has not done anything with the second expression.
Your grammar matches exactly one statement, assuming you are showing it all. Ply expects the input to terminate at that point, but it doesn't so Ply complains about an unexpected number.
Let me start by saying that I understand that what I'm asking about in the title is dubious practice (as explained here), but my lack of understanding concerns the syntax involved.
When I first tried to bind a scalar to a sigilless symbol, I did this:
my \a = $(3);
thinking that $(...) would package the Int 3 in a Scalar (as seemingly suggested in the documentation), which would then be bound to symbol a. This doesn't seem to work though: the Scalar is nowhere to be found (a.VAR.WHAT returns (Int), not (Scalar)).
In the above-referenced post, raiph mentions that the desired binding can be performed using a different syntax:
my \a = $ = 3;
which works. Given the result, I suspect that the statement can be phrased equivalently, though less concisely, as: my \a = (my $ = 3), which I could then understand.
That leaves the question: why does the attempt with $(...) not work, and what does it do instead?
What $(…) does is turn a value into an item.
(A value in a scalar variable ($a) also gets marked as being an item)
say flat (1,2, (3,4) );
# (1 2 3 4)
say flat (1,2, $((3,4)) );
# (1 2 (3 4))
say flat (1,2, item((3,4)) );
# (1 2 (3 4))
Basically it is there to prevent a value from flattening. The reason for its existence is that Perl 6 does not flatten lists as much as most other languages, and sometimes you need a little more control over flattening.
The following only sort-of does what you want it to do
my \a = $ = 3;
A bare $ is an anonymous state variable.
my \a = (state $) = 3;
The problem shows up when you run that same bit of code more than once.
sub foo ( $init ) {
my \a = $ = $init; # my \a = (state $) = $init;
(^10).map: {
sleep 0.1;
++a
}
}
.say for await (start foo(0)), (start foo(42));
# (43 44 45 46 47 48 49 50 51 52)
# (53 54 55 56 57 58 59 60 61 62)
# If foo(42) beat out foo(0) instead it would result in:
# (1 2 3 4 5 6 7 8 9 10)
# (11 12 13 14 15 16 17 18 19 20)
Note that variable is shared between calls.
The first Promise halts at the sleep call, and then the second sets the state variable before the first runs ++a.
If you use my $ instead, it now works properly.
sub foo ( $init ) {
my \a = my $ = $init;
(^10).map: {
sleep 0.1;
++a
}
}
.say for await (start foo(0)), (start foo(42));
# (1 2 3 4 5 6 7 8 9 10)
# (43 44 45 46 47 48 49 50 51 52)
The thing is that sigiless “variables” aren't really variables (they don't vary), they are more akin to lexically scoped (non)constants.
constant \foo = (1..10).pick; # only pick one value and never change it
say foo;
for ^5 {
my \foo = (1..10).pick; # pick a new one each time through
say foo;
}
Basically the whole point of them is to be as close as possible to referring to the value you assign to it. (Static Single Assignment)
# these work basically the same
-> \a {…}
-> \a is raw {…}
-> $a is raw {…}
# as do these
my \a = $i;
my \a := $i;
my $a := $i;
Note that above I wrote the following:
my \a = (state $) = 3;
Normally in the declaration of a state var, the assignment only happens the first time the code gets run. Bare $ doesn't have a declaration as such, so I had to prevent that behaviour by putting the declaration in parens.
# bare $
for (5 ... 1) {
my \a = $ = $_; # set each time through the loop
say a *= 2; # 15 12 9 6 3
}
# state in parens
for (5 ... 1) {
my \a = (state $) = $_; # set each time through the loop
say a *= 2; # 15 12 9 6 3
}
# normal state declaration
for (5 ... 1) {
my \a = state $ = $_; # set it only on the first time through the loop
say a *= 2; # 15 45 135 405 1215
}
Sigilless variables are not actually variables, they are more of an alias, that is, they are not containers but bind to the values they get on the right hand side.
my \a = $(3);
say a.WHAT; # OUTPUT: «(Int)»
say a.VAR.WHAT; # OUTPUT: «(Int)»
Here, by doing $(3) you are actually putting in scalar context what is already in scalar context:
my \a = 3; say a.WHAT; say a.VAR.WHAT; # OUTPUT: «(Int)(Int)»
However, the second form in your question does something different. You're binding to an anonymous variable, which is a container:
my \a = $ = 3;
say a.WHAT; # OUTPUT: «(Int)»
say a.VAR.WHAT;# OUTPUT: «(Scalar)»
In the first case, a was an alias for 3 (or $(3), which is the same); in the second, a is an alias for $, which is a container, whose value is 3. This last case is equivalent to:
my $anon = 3; say $anon.WHAT; say $anon.VAR.WHAT; # OUTPUT: «(Int)(Scalar)»
(If you have some suggestion on how to improve the documentation, I'd be happy to follow up on it)
It seems that if I write a set to a file, it's not in a format where it can be read back in easily as a set. Here's an example:
#lang racket
(let ([out (open-output-file "test.rkt" #:exists 'replace)])
(write (set 1 2 3 4 5) out)
(close-output-port out))
This makes a file with #<set: 1 3 5 2 4>, which the reader complains about. There is a related unanswered question on the mailing list here.
The way I'm getting around it right now is by printing literally the string "(set " to a file, then all the integers with spaces, then a closing ")". Super ugly and I would like to use the reader if possible.
You can use the Racket serialization library to do this. Here's an example:
Welcome to Racket v6.4.0.7.
-> (require racket/serialize)
-> (with-output-to-file "/tmp/set.rktd"
(lambda () (write (serialize (set 1 2 3)))))
-> (with-input-from-file "/tmp/set.rktd"
(lambda () (deserialize (read))))
(set 1 3 2)
Note that a serialized value is just a special kind of s-expression, so you can manipulate it like other values (like store it in a database, write it to disk, send it over a network, etc.):
-> (serialize (set 1 2 3))
'((3)
1
(((lib "racket/private/set-types.rkt")
.
deserialize-info:immutable-custom-set-v0))
0
()
()
(0 #f (h - (equal) (1 . #t) (3 . #t) (2 . #t))))
I am studying cryptography from Cristof Paar's book. There is a question about LFSR's I have trouble with. I just can't understand one point here. Question is this:
We want to perform an attack on another LFSR-based stream cipher. In order
to process letters, each of the 26 uppercase letters and the numbers 0, 1, 2, 3, 4, 5
are represented by a 5-bit vector according to the following mapping:
A -> 0 = 00000
.
.
.
Z -> 25 = 11001
0 -> 26 = 11010
.
.
.
5 -> 31= 11111
(binary)
We happen to know the following facts about the system:
-The degree of the LFSR is m = 6.
-Every message starts with the header WPI
We observe now on the channel the following message (the fourth letter is a zero): j5a0edj2b
What are the feedback coefficients of the LFSR? (This one!)
Solution:
I can't understand the matrix in this solution where did these numbers come?
Using WPI, we have plaintext begins with
P=>(10110)(01111)(01000)
Using j5a0edj2b we have the ciphertext
C=>(01001)(11111)(00000)(11010)(00100)(00011)(01001)............
then by addition of P and C in mod 2, the key stream is
S=>(11111)(10000)(01000)....
we find the matrix from key stream
s0=1,s1=1,s2=1,s3=1,s4=1,s5=1,s6=0,s7=0,s8=0,s9=0,s10=0,s11=1 etc
For the matrix
first line.... (s0,s1,s2,s3,s4,s5)
second line....(s1,s2,s3,s4,s5,s6)
third line.....(s2,s3,s4,s5,s6,s7)
4th (s3,s4,s5,s6,s7,s8)
5th (s4,s5,s6,s7,s8,s9)
last line (s5,s6,s7,s8,s9,s10)
this calulations are given in LFSRs in details
Is there a no-fuss serialization method for Haskell, similar to Erlang's term_to_binary/binary_to_term calls? Data.Binary seems unnecessarily complicated and raw. See this example where you are basically manually encoding terms to integers.
Use Data.Binary, and one of the deriving scripts that come with the package.
It's very simple to derive Binary instances, via the 'derive' or 'deriveM' functions provided in the tools set of Data.Binay.
derive :: (Data a) => a -> String
For any 'a' in Data, it derives a Binary instance for you as a String. There's a putStr version too, deriveM.
Example:
*Main> deriveM (undefined :: Drinks)
instance Binary Main.Drinks where
put (Beer a) = putWord8 0 >> put a
put Coffee = putWord8 1
put Tea = putWord8 2
put EnergyDrink = putWord8 3
put Water = putWord8 4
put Wine = putWord8 5
put Whisky = putWord8 6
get = do
tag_ <- getWord8
case tag_ of
0 -> get >>= \a -> return (Beer a)
1 -> return Coffee
2 -> return Tea
3 -> return EnergyDrink
4 -> return Water
5 -> return Wine
6 -> return Whisky
_ -> fail "no parse"
The example you cite is an example of what the machine generated output looks like -- yes, it is all bits at the lowest level! Don't write it by hand though -- use a tool to derive it for you via reflection.