F# For Dummys - Day 7

62 阅读2分钟

Today we learn operators and do some exercises

Operators

Operators are special symbols that perform operations on one or more operands (values or variables)
operator for 2 variables:
like +: 1 + 1 = 2, the '+' here is operator, it add the left number 1 and right number 1
we introduce 6 operators

OperatorDescription
+Adds two values
-Subtracts one value from another
/Divides the left-side value with the right-side value
%Called modulus, gives the left over from dividing the left value with the right value
<>Checks if two values aren't equal
=Checks if two values are equal
  • +
let num0 = 1
let num1 = 1
let sum = num0 + num1

printfn "1 + 1 = %i" sum // output: 1 + 1 = 2
  • -
let num0 = 2
let num1 = 1
let difference = num0 - num1

printfn "2 - 1 = %i" difference // output: 2 - 1 = 1
  • /
let num0 = 4
let num1 = 2
let quotient = num0 / num1

printfn "4 / 2 = %i" quotient // output: 4 / 2 = 2
  • %
let num0 = 3
let num1 = 2
let remainder = num0 % num1

printfn "3 %% 2 = %i" remainder // output: 3 % 2 = 1
  • <>
let num0 = 3
let num1 = 2
let equal = num0 <> num1

printfn "is 3 not equals 2? %b" equal // output: is 3 not equals 2? true
  • =
let num0 = 3
let num1 = 2
let equal = num0 = num1

printfn "is 3 equals 2? %b" equal // output: is 3 equals 2? false

exercise

  1. 1 + 2 * 3 = ?
  2. (1 + 2) * 3 = ?
  3. 2 + 2 = 2 * 2?
  4. there are 20 apples for lunch, 10 students in the class, how many apples one student can get?
  5. there are 21 apples for lunch, 10 students in the class, how many apples left?

answers

  1. '*' has higher priority than +
let results = 1 + 2 * 3
printfn "1 + 2 * 3 = %i" results // output: 1 + 2 * 3 = 7
  1. () changed the priority, + inside has higher priority than *
let results = (1 + 2) * 3
printfn "(1 + 2) * 3 = %i" results // output: (1 + 2) * 9
  1. = can compare expression, the right = has higher priority than left =, which asign value of results
let results = 2 + 2 = 2 * 2
printfn "2 + 2 = 2 * 2 is %b" results // output: 2 + 2 = 2 * 2 is true
let number_of_apples = 20
let number_of_students = 10
let apples_of_each_student = number_of_apples / number_of_students
printfn "every student can get %i apple" apples_of_each_student // output: every student can get 2 apple
let number_of_apples = 21
let number_of_students = 10
let apples_left = number_of_apples % number_of_students
printfn "%i apple left after distributing" apples_left // output: 1 apple left after distributing