5

I'm trying to do the Tower of Hanoi but I don't know how to add a count incrementer. Here's my code:

open System

let disks = Int32.Parse(Console.ReadLine())

let rec hanoi num start finish =
  match num with
  | 0 -> [ ]
  | _ -> let temp = (6 - start - finish)
     (hanoi (num-1) start temp) @ [ start, finish ] @ (hanoi (num-1) temp finish)

[<EntryPoint>]
let main args =
  (hanoi disks 1 2) |> List.iter (fun pair -> match pair with
| a, b -> printf ": %A %A\n" a b)
  0

I'm trying to get it to print out something like this

1: 1 3
2: 1 2
3: 3 2
etc...

I'm aware that there is no formatting set for the

1:
2:
3:

part. I know that the proper formatting is

"%A: %A %A\n" *with some counter here* a b

however I don't know how to do this. I've looked for an answer on the web but I have not found anything. If anyone could please help me, that would be greatly appreciated.

Thank you in advance

Marc Karam
  • 445
  • 6
  • 22
  • 3
    [List.iteri](https://msdn.microsoft.com/visualfsharpdocs/conceptual/list.iteri%5b%27t%5d-function-%5bfsharp%5d) will give you the counter. – s952163 Nov 14 '16 at 22:30
  • This is irrelevant to your question, but you might want to look at using `.fsx` files and [F# interactive](https://learn.microsoft.com/en-us/dotnet/articles/fsharp/tutorials/fsharp-interactive/) when you're learning the language - you won't have to compile code at all, and you can tweak and see feedback right there in the same window. You can send code in Visual Studio to F# interactive by highlighting it and pressing `alt-enter`. – Jake Lishman Nov 14 '16 at 22:49

1 Answers1

6

s952163's comment is the correct answer here, but here's a bit more explanation to go with it.

List.iteri looks very similar to List.iter, except your function will then have two arguments - the counter and the list element. Here, that would look like

hanoi disks 1 2 |> List.iteri (fun i (a, b) -> printfn "%d: %d %d" i a b)

note: I've also included a couple of ways to simplify that line of code, by

  • removing the unnecessary brackets around the hanoi function - the pipe operator |> has very low precedence, so brackets are not usually required to separate its arguments
  • using printfn instead of printf "...\n" - the former is preferred because it will use the correct form of the line ending. On Windows, this is actually "\r\n" (though when you're writing to the console, it doesn't matter)
  • removing the pattern match from the lambda function - you're not actually pattern matching, because the tuple (a, b) is a type itself. You can get the arguments directly in the function call, and save yourself some typing.
Community
  • 1
  • 1
Jake Lishman
  • 907
  • 7
  • 18