Hello all! My brother has recently made a couple of posts regarding the 99 problems. So now it's my turn.
"Find the last but one element of a list."
Alright, so we've already found the last element of a list, now to find the second-to-last element. . .
1 #light
2
3 let listerine = [1 .. 40]
4 let prob2 = List.nth listerine (List.length listerine - 2) |> printfn "Answer: %d"
Whew!
As you can see, I went ahead and made listerine a good-old-fasioned list from 1 through 40. The prob2 is where the real interesting stuff happens. First, we're using the List.nth aggregate operator, which takes in 2 values (the list you're looking through and which position of the list you want back [0 being the first element]) and spits out an integer. The first element, as you can see, is listerine. The second element goes ahead and grabs the length (as an integer) and returns exactly the value that we want, which is 2 less than the length (39). SUCCESS: We've got a solution. But let's see if we can clean that up a bit . . .
That's something that my brother and I were thinking of a late last night. We both wanted to narrow it down to just one easy, beautiful line but weren't having much success. Anytime I tried passing listerine to the List.nth aggregate operator using the forward pipe (this guy: |> ), it would spit out gibberish because we needed two elements. After a little bit more thinking, my brother finally got it.
1 #light
2
3 let listerine = [1 .. 40] |> fun x -> List.nth x ((List.length x) -2) |> printfn "%d"
That's it! The forward pipe (this guy: |> ) kind-of applies the function order backwards, so we're pushing the values into the anonymous function. Once there, it goes through the logic just like before, except now it's done in one easy, beautiful line.
Alright! If anyone has a better, cleaner, beautiful-er implementation of problem #2, please go ahead and post it in the comments.
EDIT:
Greg M in the comments just posted an extremely elegant solution in the comments. His solution is:
1 #light
2
3 let listerine = [1; 2; 3; 4] |> fun x -> List.nth(List.rev x) 1
When looking up the element in the list (List.nth) instead of dealing with List.length, Greg went ahead and reversed the list and pulled up element 1. Simple as that!
Thanks Greg!
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5
Tags:
Categories: