Rust – Useful Resources

Rust – Useful Resources ”; Previous Next The following resources contain additional information on Rust. Please use them to get more in-depth knowledge on this. Useful Links on Rust Rust − Official Website of Rust Rust @ Wikipedia − Rust, its history and various other terms has been explained in simple language. Useful Books on Rust To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;

Monkey and Banana Problem

Prolog – Monkey and Banana Problem ”; Previous Next In this prolog example, we will see one very interesting and famous problem, The Monkey and Banana Problem. Problem Statement Suppose the problem is as given below − A hungry monkey is in a room, and he is near the door. The monkey is on the floor. Bananas have been hung from the center of the ceiling of the room. There is a block (or chair) present in the room near the window. The monkey wants the banana, but cannot reach it. So how can the monkey get the bananas? So if the monkey is clever enough, he can come to the block, drag the block to the center, climb on it, and get the banana. Below are few observations in this case − Monkey can reach the block, if both of them are at the same level. From the above image, we can see that both the monkey and the block are on the floor. If the block position is not at the center, then monkey can drag it to the center. If monkey and the block both are on the floor, and block is at the center, then the monkey can climb up on the block. So the vertical position of the monkey will be changed. When the monkey is on the block, and block is at the center, then the monkey can get the bananas. Now, let us see how we can solve this using Prolog. We will create some predicates as follows − We have some predicates that will move from one state to another state, by performing action. When the block is at the middle, and monkey is on top of the block, and monkey does not have the banana (i.e. has not state), then using the grasp action, it will change from has not state to have state. From the floor, it can move to the top of the block (i.e. on top state), by performing the action climb. The push or drag operation moves the block from one place to another. Monkey can move from one place to another using walk or move clauses. Another predicate will be canget(). Here we pass a state, so this will perform move predicate from one state to another using different actions, then perform canget() on state 2. When we have reached to the state ‘has>’, this indicates ‘has banana’. We will stop the execution. Program move(state(middle,onbox,middle,hasnot), grasp, state(middle,onbox,middle,has)). move(state(P,onfloor,P,H), climb, state(P,onbox,P,H)). move(state(P1,onfloor,P1,H), drag(P1,P2), state(P2,onfloor,P2,H)). move(state(P1,onfloor,B,H), walk(P1,P2), state(P2,onfloor,B,H)). canget(state(_,_,_,has)). canget(State1) :- move(State1,_,State2), canget(State2). Output | ?- [monkey_banana]. compiling D:/TP Prolog/Sample_Codes/monkey_banana.pl for byte code… D:/TP Prolog/Sample_Codes/monkey_banana.pl compiled, 17 lines read – 2167 bytes written, 19 ms (31 ms) yes | ?- canget(state(atdoor, onfloor, atwindow, hasnot)). true ? yes | ?- trace . The debugger will first creep — showing everything (trace) yes {trace} | ?- canget(state(atdoor, onfloor, atwindow, hasnot)). 1 1 Call: canget(state(atdoor,onfloor,atwindow,hasnot)) ? 2 2 Call: move(state(atdoor,onfloor,atwindow,hasnot),_52,_92) ? 2 2 Exit:move(state(atdoor,onfloor,atwindow,hasnot),walk(atdoor,_80),state(_80,onfloor,atwindow,hasnot)) ? 3 2 Call: canget(state(_80,onfloor,atwindow,hasnot)) ? 4 3 Call: move(state(_80,onfloor,atwindow,hasnot),_110,_150) ? 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ? 5 3 Call: canget(state(atwindow,onbox,atwindow,hasnot)) ? 6 4 Call: move(state(atwindow,onbox,atwindow,hasnot),_165,_205) ? 6 4 Fail: move(state(atwindow,onbox,atwindow,hasnot),_165,_193) ? 5 3 Fail: canget(state(atwindow,onbox,atwindow,hasnot)) ? 4 3 Redo: move(state(atwindow,onfloor,atwindow,hasnot),climb,state(atwindow,onbox,atwindow,hasnot)) ? 4 3 Exit: move(state(atwindow,onfloor,atwindow,hasnot),drag(atwindow,_138),state(_138,onfloor,_138,hasnot)) ? 5 3 Call: canget(state(_138,onfloor,_138,hasnot)) ? 6 4 Call: move(state(_138,onfloor,_138,hasnot),_168,_208) ? 6 4 Exit: move(state(_138,onfloor,_138,hasnot),climb,state(_138,onbox,_138,hasnot)) ? 7 4 Call: canget(state(_138,onbox,_138,hasnot)) ? 8 5 Call: move(state(_138,onbox,_138,hasnot),_223,_263) ? 8 5 Exit: move(state(middle,onbox,middle,hasnot),grasp,state(middle,onbox,middle,has)) ? 9 5 Call: canget(state(middle,onbox,middle,has)) ? 9 5 Exit: canget(state(middle,onbox,middle,has)) ? 7 4 Exit: canget(state(middle,onbox,middle,hasnot)) ? 5 3 Exit: canget(state(middle,onfloor,middle,hasnot)) ? 3 2 Exit: canget(state(atwindow,onfloor,atwindow,hasnot)) ? 1 1 Exit: canget(state(atdoor,onfloor,atwindow,hasnot)) ? true ? (78 ms) yes Print Page Previous Next Advertisements ”;

Rust – Data Types

Rust – Data Types ”; Previous Next The Type System represents the different types of values supported by the language. The Type System checks validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too. Rust is a statically typed language. Every value in Rust is of a certain data type. The compiler can automatically infer data type of the variable based on the value assigned to it. Declare a Variable Use the let keyword to declare a variable. fn main() { let company_string = “TutorialsPoint”; // string type let rating_float = 4.5; // float type let is_growing_boolean = true; // boolean type let icon_char = ”♥”; //unicode character type println!(“company name is:{}”,company_string); println!(“company rating on 5 is:{}”,rating_float); println!(“company is growing :{}”,is_growing_boolean); println!(“company icon is:{}”,icon_char); } In the above example, data type of the variables will be inferred from the values assigned to them. For example, Rust will assign string data type to the variable company_string, float data type to rating_float, etc. The println! macro takes two arguments − A special syntax { }, which is the placeholder The variable name or a constant The placeholder will be replaced by the variable’s value The output of the above code snippet will be − company name is: TutorialsPoint company rating on 5 is:4.5 company is growing: true company icon is: ♥ Scalar Types A scalar type represents a single value. For example, 10,3.14,”c”. Rust has four primary scalar types. Integer Floating-point Booleans Characters We will learn about each type in our subsequent sections. Integer An integer is a number without a fractional component. Simply put, the integer data type is used to represent whole numbers. Integers can be further classified as Signed and Unsigned. Signed integers can store both negative and positive values. Unsigned integers can only store positive values. A detailed description if integer types is given below − Sr.No. Size Signed Unsigned 1 8 bit i8 u8 2 16 bit i16 u16 3 32 bit i32 u32 4 64 bit i64 u64 5 128 bit i128 u128 6 Arch isize usize The size of an integer can be arch. This means the size of the data type will be derived from the architecture of the machine. An integer the size of which is arch will be 32 bits on an x86 machine and 64 bits on an x64 machine. An arch integer is primarily used when indexing some sort of collection. Illustration fn main() { let result = 10; // i32 by default let age:u32 = 20; let sum:i32 = 5-15; let mark:isize = 10; let count:usize = 30; println!(“result value is {}”,result); println!(“sum is {} and age is {}”,sum,age); println!(“mark is {} and count is {}”,mark,count); } The output will be as given below − result value is 10 sum is -10 and age is 20 mark is 10 and count is 30 The above code will return a compilation error if you replace the value of age with a floating-point value. Integer Range Each signed variant can store numbers from -(2^(n-1) to 2^(n-1) -1, where n is the number of bits that variant uses. For example, i8 can store numbers from -(2^7) to 2^7 -1 − here we replaced n with 8. Each unsigned variant can store numbers from 0 to (2^n)-1. For example, u8 can store numbers from 0 to (2^8)-1, which is equal to 0 to 255. Integer Overflow An integer overflow occurs when the value assigned to an integer variable exceeds the Rust defined range for the data type. Let us understand this with an example − fn main() { let age:u8 = 255; // 0 to 255 only allowed for u8 let weight:u8 = 256; //overflow value is 0 let height:u8 = 257; //overflow value is 1 let score:u8 = 258; //overflow value is 2 println!(“age is {} “,age); println!(“weight is {}”,weight); println!(“height is {}”,height); println!(“score is {}”,score); } The valid range of unsigned u8 variable is 0 to 255. In the above example, the variables are assigned values greater than 255 (upper limit for an integer variable in Rust). On execution, the above code will return a warning − warning − literal out of range for u8 for weight, height and score variables. The overflow values after 255 will start from 0, 1, 2, etc. The final output without warning is as shown below − age is 255 weight is 0 height is 1 score is 2 Float Float data type in Rust can be classified as f32 and f64. The f32 type is a single-precision float, and f64 has double precision. The default type is f64. Consider the following example to understand more about the float data type. fn main() { let result = 10.00; //f64 by default let interest:f32 = 8.35; let cost:f64 = 15000.600; //double precision println!(“result value is {}”,result); println!(“interest is {}”,interest); println!(“cost is {}”,cost); } The output will be as shown below − interest is 8.35 cost is 15000.6 Automatic Type Casting Automatic type casting is not allowed in Rust. Consider the following code snippet. An integer value is assigned to the float variable interest. fn main() { let interest:f32 = 8; // integer assigned to float variable println!(“interest is {}”,interest); }

Rust – Loop

Rust – Loop ”; Previous Next There may be instances, where a block of code needs to be executed repeatedly. In general, programming instructions are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages. Rust provides different types of loops to handle looping requirements − while loop for Definite Loop A loop the number of iterations of which is definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop. For Loop The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as given below Syntax for temp_variable in lower_bound..upper_bound { //statements } An example of a for loop is as shown below fn main(){ for x in 1..11{ // 11 is not inclusive if x==5 { continue; } println!(“x is {}”,x); } } NOTE: that the variable x is only accessible within the for block. Output x is 1 x is 2 x is 3 x is 4 x is 6 x is 7 x is 8 x is 9 x is 10 Indefinite Loop An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − Sr.No Name & Description 1 While The while loop executes the instructions each time the condition specified evaluates to true 2 Loop The loop is a while(true) indefinite loop Illustration − for while fn main(){ let mut x = 0; while x < 10{ x+=1; println!(“inside loop x value is {}”,x); } println!(“outside loop x value is {}”,x); } The output is as shown below − inside loop x value is 1 inside loop x value is 2 inside loop x value is 3 inside loop x value is 4 inside loop x value is 5 inside loop x value is 6 inside loop x value is 7 inside loop x value is 8 inside loop x value is 9 inside loop x value is 10 outside loop x value is 10 Illustration −loop fn main(){ //while true let mut x = 0; loop { x+=1; println!(“x={}”,x); if x==15 { break; } } } The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Output x=1 x=2 x=3 x=4 x=5 x=6 x=7 x=8 x=9 x=10 x=11 x=12 x=13 x=14 x=15 Continue Statement The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue does not exit the loop. It terminates the current iteration and starts the subsequent iteration. An example of the continue statement is given below. fn main() { let mut count = 0; for num in 0..21 { if num % 2==0 { continue; } count+=1; } println! (” The count of odd values between 0 and 20 is: {} “,count); //outputs 10 } The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement. The count of odd values between 0 and 20 is 10 Print Page Previous Next Advertisements ”;

Rust – String

Rust – String ”; Previous Next The String data type in Rust can be classified into the following − String Literal(&str) String Object(String) String Literal String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company=”Tutorials Point”. String literals are found in module std::str. String literals are also known as string slices. The following example declares two string literals − company and location. fn main() { let company:&str=”TutorialsPoint”; let location:&str = “Hyderabad”; println!(“company is : {} location :{}”,company,location); } String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below − fn main() { let company:&”static str = “TutorialsPoint”; let location:&”static str = “Hyderabad”; println!(“company is : {} location :{}”,company,location); } The above program will generate the following output − company is : TutorialsPoint location :Hyderabad String Object The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap. Syntax To create a String object, we can use any of the following syntax − String::new() The above syntax creates an empty string String::from() This creates a string with some default value passed as parameter to the from() method. The following example illustrates the use of a String object. fn main(){ let empty_string = String::new(); println!(“length is {}”,empty_string.len()); let content_string = String::from(“TutorialsPoint”); println!(“length is {}”,content_string.len()); } The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method. The output is as shown below − length is 0 length is 14 Common Methods – String Object Sr.No. Method Signature Description 1 new() pub const fn new() → String Creates a new empty String. 2 to_string() fn to_string(&self) → String Converts the given value to a String. 3 replace() pub fn replace<”a, P>(&”a self, from: P, to: &str) → String Replaces all matches of a pattern with another string. 4 as_str() pub fn as_str(&self) → &str Extracts a string slice containing the entire string. 5 push() pub fn push(&mut self, ch: char) Appends the given char to the end of this String. 6 push_str() pub fn push_str(&mut self, string: &str) Appends a given string slice onto the end of this String. 7 len() pub fn len(&self) → usize Returns the length of this String, in bytes. 8 trim() pub fn trim(&self) → &str Returns a string slice with leading and trailing whitespace removed. 9 split_whitespace() pub fn split_whitespace(&self) → SplitWhitespace Splits a string slice by whitespace and returns an iterator. 10 split() pub fn split<”a, P>(&”a self, pat: P) → Split<”a, P> , where P is pattern can be &str, char, or a closure that determines the split. Returns an iterator over substrings of this string slice, separated by characters matched by a pattern. 11 chars() pub fn chars(&self) → Chars Returns an iterator over the chars of a string slice. Illustration: new() An empty string object is created using the new() method and its value is set to hello. fn main(){ let mut z = String::new(); z.push_str(“hello”); println!(“{}”,z); } Output The above program generates the following output − hello Illustration: to_string() To access all methods of String object, convert a string literal to object type using the to_string() function. fn main(){ let name1 = “Hello TutorialsPoint , Hello!”.to_string(); println!(“{}”,name1); } Output The above program generates the following output − Hello TutorialsPoint , Hello! Illustration: replace() The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string. The replace function replaces all occurrences of the string Hello with Howdy. fn main(){ let name1 = “Hello TutorialsPoint , Hello!”.to_string(); //String object let name2 = name1.replace(“Hello”,”Howdy”); //find and replace println!(“{}”,name2); } Output The above program generates the following output − Howdy TutorialsPoint , Howdy! Illustration: as_str() The as_str() function extracts a string slice containing the entire string. fn main() { let example_string = String::from(“example_string”); print_literal(example_string.as_str()); } fn print_literal(data:&str ){ println!(“displaying string literal {}”,data); } Output The above program generates the following output − displaying string literal example_string Illustration: push() The push() function appends the given char to the end of this String. fn main(){ let mut company = “Tutorial”.to_string(); company.push(”s”); println!(“{}”,company); } Output The above program generates the following output − Tutorials Illustration: push_str() The push_str() function appends a given string slice onto the end of a String. fn main(){ let mut company = “Tutorials”.to_string(); company.push_str(” Point”); println!(“{}”,company); } Output The above program generates the following output − Tutorials Point Illustration: len() The len() function returns the total number of characters in a string (including spaces). fn main() { let fullname = ” Tutorials Point”; println!(“length is {}”,fullname.len()); } Output The above program generates the following output − length is 20 Illustration: trim() The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces. fn main() { let fullname = ” Tutorials Point rn”; println!(“Before trim “); println!(“length is {}”,fullname.len()); println!(); println!(“After trim “); println!(“length is {}”,fullname.trim().len()); } Output The above program generates the following output − Before trim length is 24 After trim length is 15 Illustration:split_whitespace() The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below − fn main(){ let msg = “Tutorials Point has good

Rust – Package Manager

Rust – Package Manager ”; Previous Next Cargo is the package manager for RUST. This acts like a tool and manages Rust projects. Some commonly used cargo commands are listed in the table below − Sr.No Command & Description 1 cargo build Compiles the current project. 2 cargo check Analyzes the current project and report errors, but don”t build object files. 3 cargo run Builds and executes src/main.rs. 4 cargo clean Removes the target directory. 5 cargo update Updates dependencies listed in Cargo.lock. 6 cargo new Creates a new cargo project. Cargo helps to download third party libraries. Therefore, it acts like a package manager. You can also build your own libraries. Cargo is installed by default when you install Rust. To create a new cargo project, we can use the commands given below. Create a binary crate cargo new project_name –bin Create a library crate cargo new project_name –lib To check the current version of cargo, execute the following command − cargo –version Illustration – Create a Binary Cargo project The game generates a random number and prompts the user to guess the number. Step 1 – Create a project folder Open the terminal and type the following command cargo new guess-game-app –bin. This will create the following folder structure. guess-game-app/ –>Cargo.toml –>src/ main.rs The cargo new command is used to create a crate. The –bin flag indicates that the crate being created is a binary crate. Public crates are stored in a central repository called crates.io https://crates.io/. Step 2 – Include references to external libraries This example needs to generate a random number. Since the internal standard library does not provide random number generation logic, we need to look at external libraries or crates. Let us use rand crate which is available at crates.io website crates.io The rand is a rust library for random number generation. Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms. The following diagram shows crate.io website and search result for rand crate. Copy the version of rand crate to the Cargo.toml file rand = “0.5.5”. [package] name = “guess-game-app” version = “0.1.0” authors = [“Mohtashim”] [dependencies] rand = “0.5.5” Step 3: Compile the Project Navigate to the project folder. Execute the command cargo build on the terminal window − Updating registry `https://github.com/rust-lang/crates.io-index` Downloading rand v0.5.5 Downloading rand_core v0.2.2 Downloading winapi v0.3.6 Downloading rand_core v0.3.0 Compiling winapi v0.3.6 Compiling rand_core v0.3.0 Compiling rand_core v0.2.2 Compiling rand v0.5.5 Compiling guess-game-app v0.1.0 (file:///E:/RustWorks/RustRepo/Code_Snippets/cargo-projects/guess-game-app) Finished dev [unoptimized + debuginfo] target(s) in 1m 07s The rand crate and all transitive dependencies (inner dependencies of rand) will be automatically downloaded. Step 4 – Understanding the Business Logic Let us now see how the business logic works for the number guessing game − Game initially generates a random number. A user is asked to enter input and guess the number. If number is less than the generated number, a message “Too low” is printed. If number is greater than the generated number, a message “Too high” is printed. If the user enters the number generated by the program, the game exits. Step 5 – Edit the main.rs file Add the business logic to main.rs file. use std::io; extern crate rand; //importing external crate use rand::random; fn get_guess() -> u8 { loop { println!(“Input guess”) ; let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect(“could not read from stdin”); match guess.trim().parse::<u8>(){ //remember to trim input to avoid enter spaces Ok(v) => return v, Err(e) => println!(“could not understand input {}”,e) } } } fn handle_guess(guess:u8,correct:u8)-> bool { if guess < correct { println!(“Too low”); false } else if guess> correct { println!(“Too high”); false } else { println!(“You go it ..”); true } } fn main() { println!(“Welcome to no guessing game”); let correct:u8 = random(); println!(“correct value is {}”,correct); loop { let guess = get_guess(); if handle_guess(guess,correct){ break; } } } Step 6 – Compile and Execute the Project Execute the command cargo run on the terminal. Make sure that the terminal points to the Project directory. Welcome to no guessing game correct value is 97 Input guess 20 Too low Input guess 100 Too high Input guess 97 You got it .. Print Page Previous Next Advertisements ”;

Prolog – Inputs and Outputs

Prolog – Inputs and Outputs ”; Previous Next In this chapter, we will see some techniques to handle inputs and outputs through prolog. We will use some built in predicates to do these tasks, and also see file handling techniques. Following topics will be discussed in detail − Handling inputs and outputs File handling using Prolog Using some external file to read lines and terms Character manipulation for input and output Constructing and decomposing atoms Consulting prolog files into other prolog program techniques. Handling input and output So far we have seen that we can write a program and the query on the console to execute. In some cases, we print something on the console, that are written in our prolog code. So here we will see that writing and reading tasks in more detail using prolog. So this will be the input and output handling techniques. The write() Predicate To write the output we can use the write() predicate. This predicate takes the parameter as input, and writes the content into the console by default. write() can also write in files. Let us see some examples of write() function. Program | ?- write(56). 56 yes | ?- write(”hello”). hello yes | ?- write(”hello”),nl,write(”world”). hello world yes | ?- write(“ABCDE”) . [65,66,67,68,69] yes From the above example, we can see that the write() predicate can write the contents into the console. We can use ’nl’ to create a new line. And from this example, it is clear that, if we want to print some string on the console, we have to use single quotes (‘string‘). But if we use double quote (“string”), then it will return a list of ASCII values. The read() Predicate The read() predicate is used to read from console. User can write something in the console, that can be taken as input and process it. The read() is generally used to read from console, but this can also be used to read from files. Now let us see one example to see how read() works. Program cube :- write(”Write a number: ”), read(Number), process(Number). process(stop) :- !. process(Number) :- C is Number * Number * Number, write(”Cube of ”),write(Number),write(”: ”),write(C),nl, cube. Output | ?- [read_write]. compiling D:/TP Prolog/Sample_Codes/read_write.pl for byte code… D:/TP Prolog/Sample_Codes/read_write.pl compiled, 9 lines read – 1226 bytes written, 12 ms (15 ms) yes | ?- cube. Write a number: 2. Cube of 2: 8 Write a number: 10. Cube of 10: 1000 Write a number: 12. Cube of 12: 1728 Write a number: 8. Cube of 8: 512 Write a number: stop . (31 ms) yes | ?- The tab() Predicate The tab() is one additional predicate that can be used to put some blank-spaces while we write something. So it takes a number as an argument, and prints those many number of blank spaces. Program | ?- write(”hello”),tab(15),write(”world”). hello world yes | ?- write(”We”),tab(5),write(”will”),tab(5),write(”use”),tab(5),write(”tabs”). We will use tabs yes | ?- Reading/Writing Files In this section, we will see how we can use files to read from, and write into the files. There are some built-in predicates, that can be used to read from file and write into it. The tell and told If we want to write into a file, except the console, we can write the tell() predicate. This tell()predicate takes filename as argument. If that file is not present, then create a new file, and write into it. That file will be opened until we write the told command. We can open more than one file using tell(). When told is called, all files will be closed. Prolog Commands | ?- told(”myFile.txt”). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- told(“myFile.txt”). uncaught exception: error(existence_error(procedure,told/1),top_level/0) | ?- tell(”myFile.txt”). yes | ?- tell(”myFile.txt”). yes | ?- write(”Hello World”). yes | ?- write(” Writing into a file”),tab(5),write(”myFile.txt”),nl. yes | ?- write(“Write some ASCII values”). yes | ?- told. yes | ?- Output (myFile.txt) Hello World Writing into a file myFile.txt [87,114,105,116,101,32,115,111,109,101,32,65,83,67,73,73,32,118,97,108,117,101,115] Similarly, we can also read from files. Let us see some example of reading from file. The see and seen When we want to read from file, not from the keyboard, we have to change current input stream. So we can use see() predicate. This will take filename as input. When the read operation is completed, then we will use seen command. Sample File (sample_predicate.txt) likes(lili, cat). likes(jhon,dog). Output | ?- see(”sample_predicate.txt”), read(X), read(Y), seen, read(Z). the_end. X = end_of_file Y = end_of_file Z = the_end yes | ?- So from this example, we can see that using the see() predicate we can read from the file. Now after using seen command, the control transfers to the console again. So finally it takes input from console. Processing files of terms We have seen how to read specific contents (few lines) of a file. Now if we want to read/process all the contents of a file, we need to write a clause to process file (process_file), until we reach the end of the file. Program process_file :- read(Line), Line == end_of_file, % when Line is not not end of file, call process. process(Line). process_file :- !. % use cut to stop backtracking process(Line):- %this will print the line into the console write(Line),nl, process_file. Sample File (sample_predicate.txt) likes(lili, cat). likes(jhon,dog). domestic(dog). domestic(cat). Output | ?- [process_file]. compiling D:/TP Prolog/Sample_Codes/process_file.pl for byte code… D:/TP Prolog/Sample_Codes/process_file.pl compiled, 9 lines read – 774 bytes written, 23 ms yes | ?- see(”sample_predicate.txt”), process_file, seen. likes(lili,cat) likes(jhon,dog) domestic(dog) domestic(cat) true ? (15 ms) yes | ?- Manipulating characters Using read() and write() we can read or write the value of atoms, predicates, strings, etc. Now in this section we will see how to write single characters into the current output stream, or how to read from current input stream. So there are some predefined predicates to do these tasks. The put(C) and put_char(C) predicates We can use put(C) to write one character at a time into the current output stream. The output stream can be a file or the console. This C can be a character or an ASCII code in other version of Prolog like SWI prolog, but in GNU

Rust – Environment Setup

Rust – Environment Setup ”; Previous Next Installation of Rust is made easy through rustup, a console-based tool for managing Rust versions and associated tools. Installation on Windows Let us learn how to install RUST on Windows. Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang Double-click rustup-init.exe file. Upon clicking, the following screen will appear. Press enter for default installation. Once installation is completed, the following screen appears. From the installation screen, it is clear that Rust related files are stored in the folder − C:Users{PC}.cargobin The contents of the folder are − cargo-fmt.exe cargo.exe rls.exe rust-gdb.exe rust-lldb.exe rustc.exe // this is the compiler for rust rustdoc.exe rustfmt.exe rustup.exe Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command − C:UsersAdmin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) The compiler for Rust is rustc. To verify the compiler version, execute the following command − C:UsersAdmin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) Installation on Linux / Mac To install rustup on Linux or macOS, open a terminal and enter the following command. $ curl https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the installation is successful, the following line will appear − Rust is installed now. Great! The installation script automatically adds Rust to your system PATH after your next login. To start using Rust right away instead of restarting your terminal, run the following command in your shell to add Rust to your system PATH manually − $ source $HOME/.cargo/env Alternatively, you can add the following line to your ~/.bash_profile − $ export PATH=”$HOME/.cargo/bin:$PATH” NOTE − When you try to compile a Rust program and get errors indicating that a linker could not execute, that means a linker is not installed on your system and you will need to install one manually. Using Tutorials Point Coding Ground for RUST A Read-Evaluate-Print Loop (REPL) is an easy to use interactive shell to compile and execute computer programs. If you want to compile and execute Rust programs online within the browser, use Tutorialspoint Coding Ground. Print Page Previous Next Advertisements ”;

Rust – HelloWorld Example

Rust – HelloWorld Example ”; Previous Next This chapter explains the basic syntax of Rust language through a HelloWorld example. Create a HelloWorld-App folder and navigate to that folder on terminal C:UsersAdmin>mkdir HelloWorld-App C:UsersAdmin>cd HelloWorld-App C:UsersAdminHelloWorld-App> To create a Rust file, execute the following command − C:UsersAdminHelloWorld-App>notepad Hello.rs Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file − fn main(){ println!(“Rust says Hello to TutorialsPoint !!”); } The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !. Compile the Hello.rs file using rustc. C:UsersAdminHelloWorld-App>rustc Hello.rs Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command. C:UsersAdminHelloWorld-App>dir //lists the files in folder Hello.exe Hello.pdb Hello.rs Execute the Hello.exe file and verify the output. What is a macro? Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions. Using the println! Macro – Syntax println!(); // prints just a newline println!(“hello “);//prints hello println!(“format {} arguments”, “some”); //prints format some arguments Comments in Rust Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments. Rust supports the following types of comments − Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Example //this is single line comment /* This is a Multi-line comment */ Execute online Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result. Print Page Previous Next Advertisements ”;

Rust – Modules

Rust – Modules ”; Previous Next A logical group of code is called a Module. Multiple modules are compiled into a unit called crate. Rust programs may contain a binary crate or a library crate. A binary crate is an executable project that has a main() method. A library crate is a group of components that can be reused in other projects. Unlike a binary crate, a library crate does not have an entry point (main() method). The Cargo tool is used to manage crates in Rust. For example, the network module contains networking related functions and the graphics module contains drawing-related functions. Modules are similar to namespaces in other programming languages. Third-party crates can be downloaded using cargo from crates.io. Sr.No Term & Description 1 crate Is a compilation unit in Rust; Crate is compiled to binary or library. 2 cargo The official Rust package management tool for crates. 3 module Logically groups code within a crate. 4 crates.io The official Rust package registry. Syntax //public module pub mod a_public_module { pub fn a_public_function() { //public function } fn a_private_function() { //private function } } //private module mod a_private_module { fn a_private_function() { } } Modules can be public or private. Components in a private module cannot be accessed by other modules. Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public. Functions within a public module must also be made public. Illustration: Defining a Module The example defines a public module − movies. The module contains a function play() that accepts a parameter and prints its value. pub mod movies { pub fn play(name:String) { println!(“Playing movie {}”,name); } } fn main(){ movies::play(“Herold and Kumar”.to_string()); } Output Playing movie Herold and Kumar Use Keyword The use keyword helps to import a public module. Syntax use public_module_name::function_name; Illustration pub mod movies { pub fn play(name:String) { println!(“Playing movie {}”,name); } } use movies::play; fn main(){ play(“Herold and Kumar “.to_string()); } Output Playing movie Herold and Kumar Nested Modules Modules can also be nested. The comedy module is nested within the english module, which is further nested in the movies module. The example given below defines a function play inside the movies/english/comedy module. pub mod movies { pub mod english { pub mod comedy { pub fn play(name:String) { println!(“Playing comedy movie {}”,name); } } } } use movies::english::comedy::play; // importing a public module fn main() { // short path syntax play(“Herold and Kumar”.to_string()); play(“The Hangover”.to_string()); //full path syntax movies::english::comedy::play(“Airplane!”.to_string()); } Output Playing comedy movie Herold and Kumar Playing comedy movie The Hangover Playing comedy movie Airplane! Illustration – Create a Library Crate and Consume in a Binary Crate Let us create a library crate named movie_lib, which contains a module movies. To build the movie_lib library crate, we will use the tool cargo. Step 1 – Create Project folder Create a folder movie-app followed by a sub-folder movie-lib. After the folder and sub-folder are created, create an src folder and a Cargo.toml file in this directory. The source code should go in the src folder. Create the files lib.rs and movies.rs in the src folder. The Cargo.toml file will contain the metadata of the project like version number, author name, etc. The project directory structure will be as shown below − movie-app movie-lib/ –>Cargo.toml –>src/ lib.rs movies.rs Step 2 – Edit the Cargo.toml file to add project metadata [package] name = “movies_lib” version = “0.1.0” authors = [“Mohtashim”] Step 3 – Edit the lib.rs file. Add the following module definition to this file. pub mod movies; The above line creates a public module − movies. Step 4 – Edit the movies.rs file This file will define all functions for the movies module. pub fn play(name:String){ println!(“Playing movie {} :movies-app”,name); } The above code defines a function play() that accepts a parameter and prints it to the console. Step 5 – Build the library crate Build app using the cargo build command to verify if the library crate is structured properly. Make sure you are at root of project − the movie-app folder. The following message will be displayed in the terminal if the build succeeds. D:Rustmovie-lib> cargo build Compiling movies_lib v0.1.0 (file:///D:/Rust/movie-lib) Finished dev [unoptimized + debuginfo] target(s) in 0.67s Step 6 – Create a test application Create another folder movie-lib-test in the movie-app folder followed by a Cargo.toml file and the src folder. This project should have main method as this is a binary crate, which will consume the library crate created previously. Create a main.rs file in the src folder. The folder structure will be as shown. movie-app movie-lib // already completed movie-lib-test/ –>Cargo.toml –>src/ main.rs Step 7 – Add the following in the Cargo.toml file [package] name = “test_for_movie_lib” version = “0.1.0” authors = [“Mohtashim”] [dependencies] movies_lib = { path = “../movie-lib” } NOTE − The path to the library folder is set as dependencies. The following diagram shows the contents of both the projects. Step 8 – Add the following to main.rs file extern crate movies_lib; use movies_lib::movies::play; fn main() { println!(“inside main of test “); play(“Tutorialspoint”.to_string()) } The above code imports an external package called movies_lib. Check the Cargo.toml of current project to verify the crate name. Step 9 – Use of cargo build and cargo run We will use the cargo build and cargo run to build the binary project and execute it as shown below − Print Page Previous Next Advertisements ”;