A Babel of Languages on CodinGame
TBali
66.9K views
F#
Checking the sample code
(Contributed by Djoums):
1
2
3
4
5
6
7
8
9
10
11
12
13
open System
open System.Text.RegularExpressions
(* Console.In.ReadLine().ToCharArray() *)
"CG".ToCharArray()
|> Array.map (fun c -> Convert.ToString(int c, 2).PadLeft(7, '0'))
|> String.Concat
|> fun s -> Regex.Matches(s, "(.)\1*")
|> Seq.map (fun m -> m.ToString())
|> Seq.map (fun s -> (if s.[0] = '1' then "0 " else "00 ") + (String.replicate s.Length "0"))
|> String.concat " "
|> printfn "%s"
Looking at the syntax
- This is very different from an imperative style code! A proper introduction to functional programming (FP) is unfortunately beyond the scope of this playground.
|>
is the pipe forward operator, used to chain the function calls.- Comments are between
(*
and*)
. Don't ask... - There are some function names (
Convert.ToString
andPadLeft
) which look exactly the same as in our C# solution. This is not a coincidence. As C#, F# and VB .NET are all targeting Microsoft's Common Language Infrastructure (CLI) on .NET Core, they share some of the standard libraries. fun x ->
defines anonymous functions on the fly.if
..then
..else
is not a conditional statement, but a conditional expression so it returns a result.
Other characteristics
F# defines itself as "functional-first" programming language. Unlike Haskell, which is pure, uncompromising FP, with F# you can mix in some imperative or object-oriented style in your code, when it makes sense.
However, this can be abused. To demonstrate, I show an F# Chuck Norris
solution in imperative style. Don't try this at home! :-)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
open System
(* let m = Console.In.ReadLine() *)
let m = "CG"
let c = [| "00"; "0" |]
let mutable b = ""
for ch in m do
b <- b + Convert.ToString(ch |> int, 2).PadLeft(7, '0')
let mutable a = ""
a <- a + c.[(b.[0] |> int) - ('0' |> int)] + " 0"
for i = 1 to (String.length b) - 1 do
if b.[i] = b.[i - 1] then
a <- a + "0"
else
a <- a + " " + c.[(b.[i] |> int) - ('0' |> int)] + " 0"
(* eprintfn "Debug message" *)
printfn "%s" a
Resources to check
Coming next...
The natural choice for the next section is the "most-FP language of all FP languages", Haskell...
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.