繁体   English   中英

如何在 F# 中编写 Fizzbuzz

[英]How to code Fizzbuzz in F#

我目前正在学习 F# 并尝试了(一个非常)简单的 FizzBu​​zz 示例。

这是我的初步尝试:

for x in 1..100 do 
    if x % 3 = 0 && x % 5 = 0 then printfn "FizzBuzz"  
    elif x % 3 = 0 then printfn "Fizz"
    elif x % 5 = 0 then printfn "Buzz"
    else printfn "%d" x

什么解决方案可以使用 F# 来解决这个问题更优雅/简单/更好(解释原因)?

注意:FizzBu​​zz 问题是通过数字 1 到 100,并且每 3 的倍数打印 Fizz,每 5 的倍数打印 Buzz,3 和 5 的每个倍数都打印 FizzBu​​zz。 否则,将显示简单的数字。

谢谢 :)

我认为您已经有了“最佳”解决方案。

如果你想炫耀更多的功能/F#-isms,你可以做例如

[1..100] 
|> Seq.map (function
    | x when x%5=0 && x%3=0 -> "FizzBuzz"
    | x when x%3=0 -> "Fizz"
    | x when x%5=0 -> "Buzz"
    | x -> string x)
|> Seq.iter (printfn "%s")

并使用列表、序列、映射、迭代器、模式和部分应用程序。

[1..100]    // I am the list of numbers 1-100.  
            // F# has immutable singly-linked lists.
            // List literals use square brackets.

|>          // I am the pipeline operator.  
            // "x |> f" is just another way to write "f x".
            // It is a common idiom to "pipe" data through
            // a bunch of transformative functions.

   Seq.map  // "Seq" means "sequence", in F# such sequences
            // are just another name for IEnumerable<T>.
            // "map" is a function in the "Seq" module that
            // applies a function to every element of a 
            // sequence, returning a new sequence of results.

           (function    // The function keyword is one way to
                        // write a lambda, it means the same
                        // thing as "fun z -> match z with".
                        // "fun" starts a lambda.
                        // "match expr with" starts a pattern
                        // match, that then has |cases.

    | x when x%5=0 && x%3=0 
            // I'm a pattern.  The pattern is "x", which is 
            // just an identifier pattern that matches any
            // value and binds the name (x) to that value.
            // The "when" clause is a guard - the pattern
            // will only match if the guard predicate is true.

                            -> "FizzBuzz"
                // After each pattern is "-> expr" which is 
                // the thing evaluated if the pattern matches.
                // If this pattern matches, we return that 
                // string literal "FizzBuzz".

    | x when x%3=0 -> "Fizz"
            // Patterns are evaluated in order, just like
            // if...elif...elif...else, which is why we did 
            // the 'divisble-by-both' check first.

    | x when x%5=0 -> "Buzz"
    | x -> string x)
            // "string" is a function that converts its argument
            // to a string.  F# is statically-typed, so all the 
            // patterns have to evaluate to the same type, so the
            // return value of the map call can be e.g. an
            // IEnumerable<string> (aka seq<string>).

|>          // Another pipeline; pipe the prior sequence into...

   Seq.iter // iter applies a function to every element of a 
            // sequence, but the function should return "unit"
            // (like "void"), and iter itself returns unit.
            // Whereas sequences are lazy, "iter" will "force"
            // the sequence since it needs to apply the function
            // to each element only for its effects.

            (printfn "%s")
            // F# has type-safe printing; printfn "%s" expr
            // requires expr to have type string.  Usual kind of
            // %d for integers, etc.  Here we have partially 
            // applied printfn, it's a function still expecting 
            // the string, so this is a one-argument function 
            // that is appropriate to hand to iter.  Hurrah!

我的例子只是对'ssp'发布的代码的一个小改进。 它使用参数化的活动模式(将除数作为参数)。 这里有一个更深入的解释:

下面定义了一个活动模式,我们稍后可以在match表达式中使用它来测试值i是否可以被值divisor 当我们写:

match 9 with
| DivisibleBy 3 -> ...

...这意味着值 '9' 将作为i传递给以下函数,值3将作为divisor传递。 名称(|DivisibleBy|_|)是一种特殊的语法,这意味着我们正在声明一个活动模式(并且名称可以出现在->左侧的match|_|位表示模式可能会失败(当值不能被divisor整除时,我们的示例失败)

let (|DivisibleBy|_|) divisor i = 

  // If the value is divisible, then we return 'Some()' which
  // represents that the active pattern succeeds - the '()' notation
  // means that we don't return any value from the pattern (if we
  // returned for example 'Some(i/divisor)' the use would be:
  //     match 6 with 
  //     | DivisibleBy 3 res -> .. (res would be asigned value 2)
  // None means that pattern failed and that the next clause should 
  // be tried (by the match expression)
  if i % divisor = 0 then Some () else None 

现在我们可以迭代所有数字并使用match (或使用Seq.iter或其他答案中显示的其他技术)将它们与模式(我们的活动模式) match

for i in 1..100 do
  match i with
  // & allows us to run more than one pattern on the argument 'i'
  // so this calls 'DivisibleBy 3 i' and 'DivisibleBy 5 i' and it
  // succeeds (and runs the body) only if both of them return 'Some()'
  | DivisibleBy 3 & DivisibleBy 5 -> printfn "FizzBuzz"
  | DivisibleBy 3 -> printfn "Fizz" 
  | DivisibleBy 5 -> printfn "Buzz" 
  | _ -> printfn "%d" i

有关 F# 活动模式的更多信息,请参阅MSDN 文档链接 我认为如果您删除所有注释,代码会比原始版本更具可读性。 它显示了一些非常有用的技巧:-),但在你的情况下,任务相对容易......

还有一种 F# 风格的解决方案(即使用 Active Patterns):

let (|P3|_|) i = if i % 3 = 0 then Some i else None
let (|P5|_|) i = if i % 5 = 0 then Some i else None

let f = function
  | P3 _ & P5 _ -> printfn "FizzBuzz"
  | P3 _        -> printfn "Fizz"
  | P5 _        -> printfn "Buzz"
  | x           -> printfn "%d" x

Seq.iter f {1..100}
//or
for i in 1..100 do f i

添加更多可能的答案 - 这是另一种没有模式匹配的方法。 它使用Fizz + Buzz = FizzBuzz的事实,因此您实际上不需要测试所有三种情况,您只需要查看它是否可以被 3 整除(然后打印“Fizz”)并查看它是否可整除按 5(然后打印“Buzz”),最后打印一个新行:

for i in 1..100 do
    for divisor, str in [ (3, "Fizz"); (5, "Buzz") ] do
        if i % divisor = 0 then printf "%s" str
    printfn ""

嵌套的for循环在第一次迭代中将 3 和“Fizz”分配给divisorstr ,然后在第二次迭代中分配第二对值。 好处是,当值可被 7 整除时,您可以轻松添加“Jezz”的打印:-) ...以防解决方案的可扩展性受到关注!

还有一个:

let fizzy num =     
   match num%3, num%5 with      
      | 0,0 -> "fizzbuzz"
      | 0,_ -> "fizz"
      | _,0 -> "buzz"
      | _,_ -> num.ToString()

[1..100]
  |> List.map fizzy
  |> List.iter (fun (s:string) -> printfn "%s" s)

我发现这是一个更具可读性的答案编辑的灵感来自其他人

let FizzBuzz n =
    match n%3,n%5 with
    | 0,0 -> "FizzBuzz"
    | 0,_ -> "Fizz"
    | _,0 -> "Buzz"
    | _,_ -> string n

[1..100]
|> Seq.map (fun n -> FizzBuzz n)
|> Seq.iter (printfn "%s")

我找不到不包括测试i % 15 = 0的工作解决方案。 我一直觉得不测试是这个“愚蠢”任务的一部分。 请注意,这可能不是惯用的 F#,因为它是我使用该语言编写的第一个程序。

for n in 1..100 do 
  let s = seq { 
    if n % 3 = 0 then yield "Fizz"
    if n % 5 = 0 then yield "Buzz" } 
  if Seq.isEmpty s then printf "%d"n
  printfn "%s"(s |> String.concat "")

这是我的版本:

//initialize array a with values from 1 to 100
let a = Array.init 100 (fun x -> x + 1)

//iterate over array and match *indexes* x
Array.iter (fun x ->
    match x with
        | _ when x % 15 = 0 -> printfn "FizzBuzz"
        | _ when x % 5 = 0 -> printfn "Buzz"
        | _ when x % 3 = 0 -> printfn "Fizz"
        | _ -> printfn "%d" x
) a

这是我在 F# 中的第一个程序。

这并不完美,但我认为开始学习 F# 的人(如我 :))可以很快弄清楚这里发生了什么。

但是我想知道在上面的模式匹配中匹配任何_x本身有什么区别?

这是一个强调碳化的通用元组列表的版本:

let carbonations = [(3, "Spizz") ; (5, "Fuzz"); (15, "SpizzFuzz");
                    (30, "DIZZZZZZZZ"); (18, "WHIIIIII")]

let revCarbonated = carbonations |> List.sort |> List.rev

let carbonRoute someCarbonations findMe =
    match(List.tryFind (fun (x,_) -> findMe % x = 0) someCarbonations) with
        | Some x -> printfn "%d - %s" findMe (snd x)
        | None -> printfn "%d" findMe

let composeCarbonRoute = carbonRoute revCarbonated

[1..100] |> List.iter composeCarbonRoute

我不喜欢所有这些重复的字符串,这是我的:

open System
let ar = [| "Fizz"; "Buzz"; |]
[1..100] |> List.map (fun i ->
    match i % 3 = 0, i % 5 = 0 with
        | true, false ->  ar.[0]
        | false, true ->  ar.[1] 
        | true, true ->  ar |> String.Concat
        | _ -> string i
    |> printf "%s\n"
)
|> ignore

这是一个排除模检查的尝试

let DivisibleBy x y = y % x = 0
[ 1 .. 100 ]
|> List.map (function
    | x when DivisibleBy (3 * 5) x -> "fizzbuzz"
    | x when DivisibleBy 3 x -> "fizz"
    | x when DivisibleBy 5 x -> "buzz"
    | x -> string x)
|> List.iter (fun x -> printfn "%s" x)

这是我改进它的方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM