Tag Archives: recursion

Generating F# Sequences From Console Input

I got a very nice answer on SO to why a function was not executing.

open System
open System.Collections.Generic
open System.Text
open System.IO
#nowarn "40"

let rec readlines () =
     seq {
           let line = Console.ReadLine()
           if not (line.Equals("")) then
              yield line
              yield! readlines ()

let main argv =
      let inSeq = readlines ()

      |> Seq.length
      |> printfn "%d lines read"

      // This will keep it alive enough to read your output
      Console.ReadKey() |> ignore

Leave a comment

Filed under F#

Versatile into

Given a Clojure list

(defn test-list '(a b c d))

and working through 99 Lisp problems and the particular problem of reversing a simple list, I’ve struggled to avoid using recursion and Clojure’s reverse function. I am working through those problems to obtain more familiarity and confidence in working with sequences.

The following sample will move one element to the end, but I want to keep going until the end of the list.

(defn rev-seq
  (concat (pop s1) (list (peek s1))))
  (b c d a)


(repeat (count test-list) (rev-seq-elem test-list))
  ((b c d a) (b c d a) (b c d a) (b c d a))

did not help either.

And then, I remembered


which performs the accumulation and reversal all very nicely.

repl-test.core=> (into () test-list)
(d c b a)


Filed under Clojure

Bringing Home The Row Number

This solution came from one of my Stackoverflow. I wanted to find the row number where a value match took place.

The solution accepts a sequence of sequences, rows, a comparision value, val, and a index in which to perform the compare, col-idx.

(defn ret-match-row
"Searches a sequences of sequences -- rows -- at a specific column col-idx,
and returns the index of the first match and then stops."

[rows val col-idx]

(loop [[row & rows] rows
pos 0]
(not row) nil
(= val (nth row col-idx)) pos
:not-found (recur rows (inc pos)))))

(ret-match-row [[44 2 3 4 5][1 6 7 8 10][11 12 13 14 15]] 11 0)
--> 2

Leave a comment

Filed under Clojure, Functional Programming

Clojure: To Recurse or Not To Recurse

As I start week number 5 of my CodeLesson Clojure course and look at programming examples, it is clear to me that when to use recursion or not is a fuzzy science. Most Clojure text books talk about using sequences wherever possible and not even using loop/recur (Clojure’s tail recursion method)  let alone recursion without loop/recur. The Clojure Google Groups even called this method low-level while pushing using sequences.

One assignment in particular I found particularly tricky, because it involved how to make change for some number of dollar bills, and the official solution used recursion even without wrapping the sequence inside a lazy-seq function. So, I conclude individual preference and what makes sense will have to prevail concerning Clojure and recursion.


Filed under Clojure