Extracting Leaf paths from n-ary tree in F#

后端 未结 2 1247
傲寒
傲寒 2021-01-18 10:59

Inspired by this question, I wanted to try my hand at the latest ponder this challenge, using F#

My approach is probably completely off course, but in the course of

2条回答
  •  既然无缘
    2021-01-18 11:35

    Regarding laziness - You can make this lazy by using F# "seq" type instead of "list" type. Here is an example:

    let rec visitor2 lst tree =
      match tree with
      | Branch(n, sub) -> Seq.map_concat (visitor2 (lst * 10 + n)) sub
      | Leaf(n) ->
          seq { do printfn "--yielding: %d" (lst * 10 + n)
                yield lst * 10 + n };;
    

    The "seq" thing is a sequence expression, which represents a lazy stream of values. I added "printfn" to the code, so we can track how things are executing:

    > visitor2 0 tr |> Seq.take 2;;
    --yielding: 13
    --yielding: 124
    val it : seq = seq [13; 124]
    

    You can probably use something like Seq.first to find the first value which represents the result.

提交回复
热议问题