(lab 5) feat: add Conditional Traversal approach

main
Artem-Darius Weber 3 months ago
parent 939761bddb
commit 4b2323e0b1

@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
</Project>

@ -0,0 +1,46 @@
// For more information see https://aka.ms/fsharp-console-apps
printfn "Hello from F#"
// f - operator
// init - initial value
// predicate - filter condition
let rec traverseNumberWithCondition' n f init predicate =
match n with
| 0 -> init
| n ->
let digit = n % 10
let newAcc =
match predicate digit with
| true -> f init digit
| false -> init
traverseNumberWithCondition' (n / 10) f newAcc predicate
let traverseNumberWithCondition n f init predicate =
traverseNumberWithCondition' n f init predicate
[<EntryPoint>]
let main argv =
System.Console.WriteLine("Введите число:")
let number = System.Console.ReadLine() |> int
// Сумма четных цифр
let isEven x = x % 2 = 0
let sumEven = traverseNumberWithCondition number (fun x y -> x + y) 0 isEven
System.Console.WriteLine($"Сумма четных цифр: {sumEven}")
// Произведение нечетных цифр
let isOdd x = x % 2 <> 0
let mulOdd = traverseNumberWithCondition number (fun x y -> x * y) 1 isOdd
System.Console.WriteLine($"Произведение нечетных цифр: {mulOdd}")
// Максимальная цифра, большая 5
let isGreaterThan5 x = x > 5
let maxGreater5 = traverseNumberWithCondition number (fun x y -> max x y) 0 isGreaterThan5
System.Console.WriteLine($"Максимальная цифра > 5: {maxGreater5}")
// Минимальная цифра из цифр, делящихся на 3
let isDivisibleBy3 x = x > 0 && x % 3 = 0
let minDivBy3 = traverseNumberWithCondition number (fun x y -> min x y) System.Int32.MaxValue isDivisibleBy3
System.Console.WriteLine($"Минимальная цифра, делящаяся на 3: {minDivBy3}")
0
Loading…
Cancel
Save