Skip to content

Hw 4#4

Open
AnNyiiik wants to merge 16 commits intomainfrom
HW_4
Open

Hw 4#4
AnNyiiik wants to merge 16 commits intomainfrom
HW_4

Conversation

@AnNyiiik
Copy link
Owner

@AnNyiiik AnNyiiik commented Apr 5, 2024

No description provided.

Comment on lines +9 to +12
let f (x : int) = (*) x
let f_withoutX = f
let func = f_withoutX >> List.map
func

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ожидалась point-free запись без использования промежуточных let.

Comment on lines +7 to +11
type Person =
val Name : string
val Number : string

new (name, phone) = { Name = name; Number = phone;}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
type Person =
val Name : string
val Number : string
new (name, phone) = { Name = name; Number = phone;}
type Person = { Name: string; Number: string }

module Brackets =

let checkSequence (sequence : string) =
let rec checkRec sequence stack position =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пусть стек будет типа char list, это повзолит избежать конкатенаций строк и позволит использовать паттерн-матчинг

Comment on lines +14 to +16
if (String.length stack = 0) then false
else
if ((bracket = ')' && stack.[0] = '(') || (bracket = ']' && stack.[0] = '[') || (bracket = '}' && stack.[0] = '{')) then

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужно использовать паттерн матчинг на stack

else
let bracket = sequence.[position]
match bracket with
| '[' | '{' | '(' ->
Copy link

@DedSec256 DedSec256 May 30, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно завести отдельные небольшие функции, которые проверят, что скобочка открывающаяся, закрывающаяся и какие скобки образуют пару.

Или, как вариант, Map

}

let testCasesFalse =
seq {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужны тесты на "", ")", "("

Comment on lines +14 to +15
let mutable errors = 0
let mutable data = []

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нельзя использовать мутабельное состояние

Comment on lines +51 to +67
let rec ``find name or phone`` code =
if (errors > 5) then ()
if code = 2 then printfn "enter the name:\n" else printfn "enter the phone:\n"
let item = Console.ReadLine()
if (code = 2 && not (name_regex().IsMatch(item)) || code = 3 && not (phone_regex().IsMatch(item))) then
printfn "incorrect data, try again\n"
errors <- errors + 1
``find name or phone`` code
else
errors <- 0
if code = 2 then
match findByName item data with
| None -> printfn "%s" "there is no such name\n"
| Some name -> printfn "%s" (name.ToString())
else match findByPhone item data with
| None -> printfn "%s" "there is no such number\n"
| Some number -> printfn "%s" (number.ToString())

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

разделите функцию на две

To read data from file and save it to phone book press 6:\n"


let mutable errors = 0

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

точно ли нам эта логика с ошибками нужна?

Comment on lines +13 to +14
if List.exists(fun (p : Person) -> p.Number = person.Number) data
then data else person :: data

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я бы делал, в случае добавления дубликата, более очевидный тип ошибки, нежели скрывать её за возвращением того же набора данных

Comment on lines +18 to +23
let comparePersons (p1 : Person) (p2 : Person) =
if p1.Name < p2.Name then -1 else
if p1.Name = p2.Name then
if p1.Number < p2.Number then -1
else 1
else 1

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это не нужно, рекорды сравниваются структурно через обычное =

let funcInitial x l = List.map (fun y -> y * x) l
let funcWithoutL1 x = List.map (fun y -> y * x)
let funcWithoutL2 x = List.map (fun y -> (*) y x)
let funcWithoutL3 x = List.map << (fun y -> (*) y) <| x

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let funcWithoutL3 x = List.map << (fun y -> (*) y) <| x
let funcWithoutL3 x = (List.map << (fun y -> (*) y)) x

Comment on lines +13 to +14
match bracket with
| '[' | '{' | '(' ->
Copy link

@DedSec256 DedSec256 May 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

воспользуйтесь bracketPairs.Keys.Contains, чтобы не дублировать логику


let checkSequence (sequence : string) =
let rec checkRec sequence stack position counter =
if (position = String.length sequence) then

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (position = String.length sequence) then
if (position = sequence.Length) then

Comment on lines +19 to +20
if (bracket = bracketPairs.[stack.[0]]) then
checkRec sequence stack.[1..(counter - 1)] (position + 1) (counter - 1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давайте использовать паттерн матчинг, чтобы проверять голову и хвост у stack

Comment on lines +25 to +26
let dataConvertToString = " Tom 89019892909 \n Alice 83890198101 \n John 82839281789 \n Bob +72898271890 \n Hanna +71289019813 \n Sara 81278918789 \n"
[<Test>]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let dataConvertToString = " Tom 89019892909 \n Alice 83890198101 \n John 82839281789 \n Bob +72898271890 \n Hanna +71289019813 \n Sara 81278918789 \n"
[<Test>]
let dataConvertToString = " Tom 89019892909 \n Alice 83890198101 \n John 82839281789 \n Bob +72898271890 \n Hanna +71289019813 \n Sara 81278918789 \n"
[<Test>]

И вообще, это data |> List.fold ...? Правда ли, что если мы в data что-то поменяем, а тут нет, беда будет? :)

(findByName "Sara" data).Value |> should equal "81278918789"
findByName "Kat" data |> should equal None

let dataWrite = "Tom 89019892909\nAlice 83890198101\nJohn 82839281789\nBob +72898271890\nHanna +71289019813\nSara 81278918789"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кстати, если оно для одного теста, чтоит внутри теста и объявлять

open System
open System.Text.RegularExpressions

module PhoneBook =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы ещё сказал, что надо комментарии

Comment on lines +1 to +2
namespace PhoneBook
open System

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
namespace PhoneBook
open System
namespace PhoneBook
open System


type Person = { Name: string; Number: string }

let phone_regex () = Regex(@"(\+7|7|8)+\d{10}", RegexOptions.Compiled)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В .NET используют camelCase, это ж не Питон

let addRecord (person : Person) data =
if List.exists(fun (p : Person) -> p.Number = person.Number) data
then
invalidArg "" "incorrect data: the number already exists"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • имя параметра пустое, нехорошо
  • в ФП не любят исключения, они неявны и вызывающий может быть неготов к тому, что они бросаются. Сделайте более по-ФПшному

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не поправлено


Some code

let rec ``add record`` data =

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зачем такие странные имена

let phoneRegex () = Regex(@"(\+7|7|8)+\d{10}", RegexOptions.Compiled)
let nameRegex () = Regex(@"[A-Z][a-z]+", RegexOptions.Compiled)

///Add new record to the data

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
///Add new record to the data
/// Add new record to the data

let addRecord (person : Person) data =
if List.exists(fun (p : Person) -> p.Number = person.Number) data
then
invalidArg "" "incorrect data: the number already exists"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не поправлено

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants