Using data arrays how do i ouput arrays of data after converting to fahrenheit. – Haskell

I want to take the temperature from all the data in the cities array and output the data in fahrenheit.

Everything ive tried doesnt seem to work, as you can see getAllTempsF was my most recent attempt.

C to F is (c*1.8)+18

data City = City { cityName :: String
                        , temperature :: [Double] 

city1 = City {cityName = "city1", temperature = [4.50,6.50,5.0,6.48,8.54]}
city2 = City {cityName = "city2", temperature = [6.35,5.12,3.21,3.25,4.56]}
city3 = City {cityName = "city3", temperature = [7.3,5.32,4.4,4.6]}

cities :: [City]
cities = [city1,city2,city3]

getAllNames :: [City] -> [String]
getAllNames x = map cityName x

getAllTemps :: [City] -> [[Double]]
getAllTemps x = map temperature x

getAllTempsF :: [City] -> [[Double]]
getAllTempsF [] = 1
getAllTempsF (x:xs) = [((x * 1.8) + 32)..] >>  getAllTempsF xs

>Solution :

You’ve already used map, which means "do something to each element of the list", in getAllTemps. getAllTempsF can also be phrased as "do something to each element of the list", where "something" in this case is some math. The only difference is that we’re dealing with a list of lists, rather than a single list. We can still use map to write this function; we just have to do it twice.

getAllTempsF :: [City] -> [[Double]]
getAllTempsF xs = map (map (\x -> x * 1.8 + 32)) $ getAllTemps xs

Now we have it in a list of lists. You mentioned printing out the data, and to do that we’ll use forM_, which is about like map but for side effects rather than values.

printOutTemps :: [City] -> IO ()
printOutTemps cities = do
  -- Get each city, together with its temperatures in a list.
  let cityData = zip cities (getAllTempsF cities)
  -- For each one... do some IO.
  forM_ cityData $ \(city, tempsF) -> do
    -- Get the temperatures as a list of strings, so we can print them out.
    let tempsStr = map show tempsF
    -- Print out the city names and the temperatures.
    putStrLn $ (cityName city) ++ " has temperatures " ++ unwords tempsStr

Try it online!

In case you haven’t found this particular resource yet, Hoogle is a great site for identifying Haskell functions. So if you don’t know what any of the functions I used in this answer do, you can always search them on Hoogle. For instance, if you don’t know what zip does, you can search zip and the first result is exactly the function you’re looking for.

Leave a Reply