## Weather Forecast

### November 5, 2010

The internet provides a rich source of data for those who are interested: stock prices, baseball statistics, the littoral area in acres of lakes in Minnesota, and much more. In the United States, the National Oceanic and Atmospheric Administration publishes daily weather forecasts at http://weather.noaa.gov/pub/data/forecasts/.

Your task is to write a program that retrieves the current weather forecast for a requested city. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

Pages: 1 2

### 9 Responses to “Weather Forecast”

1. My Haskell solution (see http://bonsaicode.wordpress.com/2010/11/05/programming-praxis-weather-forecast/ for a version with comments):

```import Network.HTTP

showWeather :: String -> String -> IO ()
showWeather state city = either print (putStrLn . rspBody) =<<
simpleHTTP (getRequest \$ "http://weather.noaa.gov/pub/data/\
\forecasts/city/" ++ state ++ "/" ++ city ++ ".txt")
```
2. novatech said

function weather() { curl http://weather.noaa.gov/pub/data/forecasts/city/\$1/\$2.txt; }
weather \$1 \$2

3. Graham said

This definitely made me think. At first I was tempted to just open the webpage itself.
This is basically a less pretty knock-off of Remco’s Haskell.

```import sys
import urllib

def weather(s, c):
a = "http://weather.noaa.gov/pub/data/forecasts/city/%s/%s.txt" % (s, c)
u = urllib.urlopen(a)
for l in u: print l
u.close()

if __name__ == '__main__':
weather(sys.argv[1], sys.argv[2])
```
4. slabounty said

A ruby version

```require 'net/http'

def display_weather(city, state)
Net::HTTP.get_print URI.parse("http://weather.noaa.gov/pub/data/forecasts/city/#{state}/#{city}.txt")
end

display_weather('bakersfield', 'ca')
```
5. Ian said

Actually, `file-exists?` and `delete-file` are standard if you include R6RS, and it is my understanding that they will be included in the R7RS too.

Anyway, I’m lazy so I used an existing http library for R6RS

```#!/usr/bin/env scheme-script
#!r6rs
(import (rnrs)
(ocelotl net http)
(ocelotl net http-client)
(srfi :48 intermediate-format-strings))

(define (display-weather state city)
(define weather-url
"http://weather.noaa.gov/pub/data/forecasts/city/~a/~a.txt")
(let-values (((response body) (http-get (format #f weather-url state city)
'((Accept-Charset . "utf-8")))))
(if (= (http-response/status-code response) 200)
(display (utf8->string body))
(display "I'm sorry, there is no weather forecast for this city\n"))))

(let ((args (command-line)))
(if (= (length args) 3)
(display-weather (cadr args) (caddr args))
(display "Usage: forecast.ss STATE CITY\n")))
```
6. Paul said

A couple of lines for powershell

7. Sorry for previous comment! it is on wrong post!
That is for “subset sums “!