Haskell List. Accounts in F #

What is the way to implement similar functionality in Haskell from a list using guards in F #

eg:

factors    ::  Int -> [Int]
factors    =   [x | x <-[1 .. n], n 'mod' x == 0]

factors 15
[1,3,5,15]

and

posInt     ::   Int -> [Int]
posInt     =    [n | n > 0]

posInt 5
[5]

posInt 0
[]
+3
source share
3 answers

gradbot is correct. The correct conversion posIntwould look like this:

let posInt n = [if n > 0 then yield n]
+4
source
let factors n = [for x in 1 .. n do if n % x = 0 then yield x]

As Kvb showed, you can use security without sequence.

let posInt n = [if n > 0 then yield n]

On a side note:
Since the list is not lazy in F #, you need to use a sequence for an infinite series.

let posInfinite = seq {1 .. Int32.MaxValue}

. , ​​ ..Net , BigInteger. , "I" . .

let posInfinite = Seq.unfold (fun i -> Some(i, i + 1I)) 1I
+4

See answer to

How to translate this Haskell to F #?

which outlines a general way to turn an understanding of a Haskell list into F # code.

(Copying here for convenience:

More generally, I think that the Haskell list views have the form suggested in the example below and the corresponding F # is shown.

// Haskell
// [e(x,y) | x <- l1, y <- l2, pred(x,y)]
// F#
[for x in l1 do
    for y in l2 do
        if pred(x,y) then
            yield e(x,y)]

)

+4
source

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


All Articles