Quantcast
Channel: Haskell data type list - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by leftaroundabout for Haskell data type list

$
0
0

First I'd recommend you actually use those type synonyms, if you define them at all:

data Car = Car Name Model Color Year Price Coin  deriving (Show)

Note that this is completely equivalent to declaring all fields String (because Model and String are just different names for exactly the same type), it's just clearer to read. Even clearer might be if you used record fields for such a type, but that wouldn't make a difference here.

Now to “create” a new car from some string properties, you want to not concatenate these properties to a list. Instead, just use the Car constructor and prepend a single car to the list.

main = do    putStrLn "Car details "    putStr "Name: "    name <- getLine    ...    let cars' = Car name model color year price coin : cars    print cars'

In case you wonder: Car foo bar baz : cars is the same as (Car foo bar baz) : (cars). In fact, Car is just used like any other function here; you could also define a helper function

redCar :: Name -> Model -> Year -> Price -> Coin -> CarredCar n m y p c = Car n m "red" y p c

and then write

   print $ redCar name model year price coin : cars

OTOH, [cars] is not a list of cars that you could prepend another car to; rather it's a list with a single element (and that element is a list of cars).

A different subject is how you update stuff in general, in Haskell. ErikR adresses how this can be done with recursion; I'd note that you can also have proper mutable variables in Haskell IO code. We generally avoid working in IO as much as possible, but if you actually write an interactive application then it's sensible enough:

import Data.IORefmain = do    knownCars <- newIORef cars    putStrLn "Car details "    ...    modifyIORef knownCars $ Car name model color year price coin    print =<< readIORef cars

Then you can follow this with

    putStrLn "Details of another car:"    ...    modifyIORef knownCars $ Car name2 model2 color2 year2 price2 coin2

and actually have both cars added. Of course this only makes sense if the whole program is actually running in a loop. (“Loop” still meaning recursion, in fact.)


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>