Problem #3

Building on what we have already the next couple should be a breeze. Problem #3 is as follows:

 "Find the K'th element of a list."

We can basically simplify problem two a little bit and get the answer for three.

    1 #light

    2 

    3 let listerine k = [1 .. 40]  |> fun x -> List.nth x k

    4 

    5 printfn "Answer: %d" (listerine 27)

This statement should look very similar to problem 2 except for two distinct differences...

  1. We are passing a parameter k to the function
  2. We are no longer calculating the second to last character but rather finding the element k. 

 Pretty straight forward but this will fail if k is out of bounds.

Microsoft.FSharp.Core.InvalidArgumentException: nth

>    at Microsoft.FSharp.Collections.ListModule.nth[T](List`1 l, Int32 n)
   at <StartupCode$FSI_0018>.FSI_0018._main()
stopped due to error

We'll look at how to get around that at a later time :)

kick it on DotNetKicks.com  


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags: ,
Categories: F#

2 Comments
Actions: E-mail | Permalink | Comment RSSRSS comment feed

Related posts

Comments

February 28. 2008 20:36

Greg M

For problems 3-5 where there is already a built-in function, you'd learn more by writing it without using the built-in. Try doing them recursively.

Greg M

March 6. 2008 01:26

Jesus DeLaTorre

I solved it using recursion.

#light
let rec p03 list k =
match list with
| y::ys -> (match k with
| 1 -> y
| _ -> if (k > 1) then p03 ys (k - 1)
else y)
| [] -> []

Jesus DeLaTorre

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

August 28. 2008 14:11