I want to convert a given integer into a base 4 string. For eg : In scala,
var str: String = Integer.toString(10, 4)
gives the output "22" ie 2*(4^1) + 2*(4^0) = 10
Im having difficulty doing this in F#. Any help is appreciated
let intToDigits baseN value : int list =
let rec loop num digits =
let q = num / baseN
let r = num % baseN
if q = 0 then
r :: digits
else
loop q (r :: digits)
loop value []
254
|> intToDigits 16
|> List.fold (fun acc x -> acc + x.ToString("X")) ""
|> printfn "%s"
254
|> intToDigits 4
|> List.fold (fun acc x -> acc + x.ToString()) ""
|> printfn "%s"
This outputs FE for the base-16 conversion and 3332 for the base-4 conversion. Note that ToString("X") works for up to base 16, so it could be used for the base-4 conversion too.
I adapted this int based solution from Stuart Lang's bigint example (which uses bigint.DivRem rather than integer operators).
I am just starting out with F# so this might be a trivial question but I am not able to understand why the pattern matching in my code acts as it does.
Quick explanation of the code:
The func calcNextMatch should recurse a list and if 2 elements are equal they should be added together.
In the end the func should return a number that is the addition of all digits that has a match with the next digit in the list.
f.ex. [1;3;2;2;5] should return 4
Code:
let rec printList l =
match l with
| head :: tail -> printf "%d " head; printList tail
| [] -> printfn ""
let rec calcNextMatch list =
printList list
match list with
| [] -> 0
| _ :: tail ->
printList tail
let h = Seq.head list
let t = Seq.tryHead tail
printfn "h: %i" h
printfn "t: %O" t
match t with
| Some h ->
printfn "TAIL t: %i is equal to HEAD h: %i" t.Value h
printfn "Calculation is: %i" (t.Value + h)
(t.Value + h) + calcNextMatch tail
| _ -> calcNextMatch tail
let sequence = [ 1;3;2;2;5 ]
let run = calcNextMatch sequence
When I run this code the problem is that the pattern-matching
does not work as I expect it.
f.ex this print output from running the script.
h: 1
t: Some(3)
TAIL t: 3 is equal to HEAD h: 3
this means that F# has matched
match t with
| Some h ->
in a case where t = Some(3) and h = 1
which translates to
match 3 with
| Some 1 ->
and that I do not understand.
The print before the matching states the value of t and h to 3 and 1 but in the pattern-matching the value of h has change to 3
How is this possible?
You can only pattern match against constant literals, otherwise the value get bounded as if was a new let-binding.
In these cases what you do normally is to add a when condition:
match t with
| Some x when x = h ->
Also notice that you can use pattern match further to simplify your code, for instance here:
| _ :: tail ->
printList tail
let h = Seq.head list
You can write:
| h :: tail ->
printList tail
Also all this portion:
| _ :: tail ->
printList tail
let h = Seq.head list
let t = Seq.tryHead tail
printfn "h: %i" h
printfn "t: %O" t
match t with
| Some h ->
printfn "TAIL t: %i is equal to HEAD h: %i" t.Value h
printfn "Calculation is: %i" (t.Value + h)
(t.Value + h) + calcNextMatch tail
becomes:
| h :: tail ->
printList tail
//printfn "h: %i" h
//printfn "t: %O" t
match tail with
| t::_ when t = h ->
printfn "TAIL t: %i is equal to HEAD h: %i" t h
printfn "Calculation is: %i" (t + h)
(t + h) + calcNextMatch tail
And you can unify all matches in one, so your whole function becomes:
let rec calcNextMatch list =
printList list
match list with
| [] -> 0
| h::x::tail when x = h -> x + h + calcNextMatch (x::tail)
| _::tail -> calcNextMatch tail
Finally, when you're done with debugging, you can remove the prints and since the last parameter of your function is the one you match against, you can use the keyword function, also use an as pattern to avoid reconstructing the list:
let rec calcNextMatch = function
| [] -> 0
| h::((x::_) as tail) when x = h -> x + h + calcNextMatch tail
| _::tail -> calcNextMatch tail
I am trying to achieve the following. Input is list [8;9;4;5;7] and output should be
"8,9,4,5,7," Note the "," in the output
I tried the following
let rec ConvertToString list =
match list with
| head :: tail -> head.ToString() + ConvertToString tail
| [] -> ""
let op= [8;9;4;5;7] |> ConvertToString
But the output which i get is val me : string = "89457"
Can anyone kindly suggest how to get get the "," in the output. The function should be generic.
You need to add the comma between the head and the converted tail, and need another case to convert the last element so you don't add a separating comma.
let rec ConvertToString list =
match list with
| [l] -> l.ToString()
| head :: tail -> head.ToString() + "," + ConvertToString tail
| [] -> ""
Note you can also define your function using String.concat:
let ConvertToString l = l |> List.map (fun i -> i.ToString()) |> String.concat ","
or String.Join:
let ConvertToString (l: 'a seq) = System.String.Join(",", l)
If you only want to allow ConvertToString to take int list arguments, you can specify the type of the input argument explicitly:
let ConvertToString (l : int list) = ...
I think this is a nice version for integer lists:
let convertToString = List.map (sprintf "%i") >> String.concat ","
or if you want a generic version:
let convertToString l = l |> List.map (sprintf "%A") |> String.concat ","
Just another way to do this:
let ConvertToString (l: int list) =
match l with
| [] -> ""
| h :: t -> List.fold (fun acc x -> acc + "," + x.ToString()) (h.ToString()) t
Trying to merge two LazyLists in F# after this question on SO. Originally wrote for matching two Lists. Modified that to get this:
let rec printLazyList (l1:LazyList<int>) (l2:LazyList<int>) =
match (l1, l2) with
| t, s when t |> LazyList.isEmpty && s |> LazyList.isEmpty -> printfn "";
| t , LazyList.Cons(h2,t2) when t |> LazyList.isEmpty -> printf "%d " h2
let a = LazyList.empty
printLazyList a t2
| LazyList.Cons(h1,t1), s when s |> LazyList.isEmpty -> printf "%d " h1
let b = LazyList.empty
printLazyList t1 b
| LazyList.Cons(h1,t1), LazyList.Cons(h2,t2) -> if h1 = h2 then
printf "%d " h1
printLazyList t1 t2
elif h1 < h2 then
printf "%d " h1
printLazyList t1 l2
else
printf "%d " h2
printLazyList l1 t2
The problem is it is giving no output. None of the conditions are being satisfied (checked this by putting a |_,_ printfn "nothing matches" at the end of the pattern matching. Is there a fundamental difference in the cons that is used in LazyList versus the :: in the usual F# lists? Because this worked for normal lists (cf. the link above).
Sorry if this is again a really n00b question. FP is looking rather difficult at this point.
If you test the function using fsi, be careful since there is a lot of noise in fsi console and your eyes may skip the line of output.
Here is a complete test (I did some cleanups by using Nil instead of isEmpty and reorganizing pattern matching for readability):
#r "FSharp.PowerPack.dll"
open LazyList
let rec printLazyList l1 l2 =
match l1, l2 with
| Nil, Nil -> printfn ""
| Nil, Cons(h2, t2) ->
printf "%d " h2
printLazyList LazyList.empty t2
| Cons(h1, t1), Nil ->
printf "%d " h1
printLazyList t1 LazyList.empty
| Cons(h1, t1), Cons(h2, t2) when h1 = h2 ->
printf "%d " h1
printLazyList t1 t2
| Cons(h1, t1), Cons(h2, t2) when h1 < h2 ->
printf "%d " h1
printLazyList t1 l2
| Cons(h1, t1), Cons(h2, t2) ->
printf "%d " h2
printLazyList l1 t2
let x = LazyList.ofList [1; 2];;
let y = LazyList.ofList [3; 4];;
printLazyList x y;;
I am currently learning F# and have tried (an extremely) simple example of FizzBuzz.
This is my initial attempt:
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
What solutions could be more elegant/simple/better (explaining why) using F# to solve this problem?
Note: The FizzBuzz problem is going through the numbers 1 to 100 and every multiple of 3 prints Fizz, every multiple of 5 prints Buzz, every multiple of both 3 AND 5 prints FizzBuzz. Otherwise, simple the number is displayed.
Thanks :)
I think you already have the "best" solution.
If you want to show off more functional/F#-isms, you could do e.g.
[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")
and use lists, sequences, map, iter, patterns, and partial application.
[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!
My example is just a minor improvement over the code posted by 'ssp'. It uses parameterized active patterns (which take the divisor as an argument). Here is a more in-depth explanation:
The following defines an active pattern that we can later use in the match
expression to test if a value i is divisible by a value divisor. When we write:
match 9 with
| DivisibleBy 3 -> ...
...it means that the value '9' will be passed to the following function as i and the value 3 will be passed as divisor. The name (|DivisibleBy|_|) is a special syntax, whith means that we're declaring an active pattern (and the name can appear in the
match on the left side of ->. The |_| bit means that the pattern can fail (our example fails when value is not divisible by 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
Now we can iterate over all the numbers and match them against patterns (our active pattern) using match (or using Seq.iter or some other technique as shown in other answers):
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
For more information on F# active patterns, here is an MSDN documentation link. I think that if you remove all the comments, the code will be slightly more readable than the original version. It shows some quite useful tricks :-), but in your case, the task is relatively easy...
Yet one solution in F# style (i.e. with Active Patterns usage):
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
To add one more possible answer - here is another approach without pattern matching. It uses the fact that Fizz + Buzz = FizzBuzz, so you don't actually need to test for all three cases, you only need to see if it is divisible by 3 (then print "Fizz") and also see if it is divisible by 5 (then print "Buzz") and finally, print a new line:
for i in 1..100 do
for divisor, str in [ (3, "Fizz"); (5, "Buzz") ] do
if i % divisor = 0 then printf "%s" str
printfn ""
The nested for loop assignes 3 and "Fizz" to divisor and str in the first iteration and then the second pair of values in the second iteration. The beneift is, you could easily add printing of "Jezz" when the value is divisible by 7 :-) ...in case that extensibility of the solution is a concern!
Here's one more:
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)
I find this to be a bit more readable answer edited was inspired a bit by the others
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")
Here is my version:
//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
This is my first program in F#.
It's not perfect, but I think someone who starts learning F# (like me :)) can figure out what happens here quite fast.
However I am wondering what is the difference between matching to any _ or to x itself in pattern matching above?
I couldn't find a working solution that didn't include testing for i % 15 = 0. I've always felt that not testing for that is part of this "stupid" assignment. Be aware that this is probably not idiomatic F# since it's my first program in the language.
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 "")
Here's a version emphasizing a generic tuple list of carbonations:
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
I don't like all these repeated strings, here's mine:
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
Here is an attempt that factors out the modulo checks
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)
Here is how I refined it