Associated Values ​​in F #

I am new to F # dealing with a trivial problem. How to check if two integers are integers? I found this pythonic approach really interesting and, IMHO, elegant. I am trying to translate it to F #, without luck. In my opinion, this is due to my inexperienced.

In any case, this is my "best" attempt:

let prime (x, y) =                                          
  if y <> 0 then
      (x, y) <| (y, x % y)
  else 
      x;; 

This should be the result, i.e. at

prime 23 13;;
- : bool = true

Obviously this will not work. What is the best approach to such a problem in F #? I come from R-programming, which requires a completely different form of thinking.

+4
source share
2 answers

Almost direct translation of related python code.

gcd, "looping construct" python, (FP " " )

let rec gcd = function
  | x, 0 -> x
  | x, y -> gcd (y, x % y)

coprime , , gcd 1

let coprime = gcd >> (=) 1

, , :

let coprime (x, y) = gcd (x, y) = 1

, ( ), , ( BigInteger.GreatestCommonDivisor bigint, )

open LanguagePrimitives

let inline gcd (x, y) =
  // we need an helper because inline and rec don't mix well
  let rec aux (x, y) =
    if y = GenericZero
    then x
    else aux (y, x % y)
  aux (x, y)

// no pointfree style, only function can be inlined not values
let inline coprime (x, y) = gcd (x, y) = GenericOne

@Henrik Hansen , ,

let (|LT|EQ|GT|) (x, y) =
  if x < y then LT
  elif x = y then EQ
  else GT

let areCoPrimes x y =
  let rec aux (x, y) =
    match x, y with
    | 0, _ | _, 0 -> false
    | LT          -> aux (x, y - x)
    | EQ          -> x = 1
    | GT          -> aux (x - y, y)
  aux (abs x, abs y)
+8

: . , Sehnsuchts , , :

let rec areCoPrimes a b =
    match a, b with
    | a, b when a < 0 -> areCoPrimes -a b
    | a, b when b < 0 -> areCoPrimes a -b
    | 0, b  -> false
    | a, 0 -> false
    | a, b when a = b -> a = 1
    | a, b when a > b -> areCoPrimes (a - b) b
    | a, b when a < b -> areCoPrimes a (b - a)

- , , .

+6

Source: https://habr.com/ru/post/1658470/


All Articles