Skip to content

Comment on Hakaru: An embedded probabilistic programming language in Haskellparent

Comments

A while ago I tried to port some of the Python code from the book Programming Collective Intelligence to Haskell, and I got stuck on the seemingly simple problem of reading and processing heterogenous collections (strings and numbers).

What is the nicer way to do it?

So I don't really consider myself a Haskell programmer, but the standard advice is to think about operation you are going to perform on those strings and numbers later, then think if there is a datatype you could create instead.

As an example, suppose I am trying to load a csv file with two fields being strings and one being Double. A list of lists representation isn't going to cut it. Instead I should make a Row datatype

  data Row = Row {field1 :: String, field2 :: String, field3 :: Double}
Then you can parse the csv file into a [Row] representation.

As an aside, if the task did involve parsing csv I suggest the cassava library which I found out about through the amazing What I Wish I Knew When Learning Haskell (http://dev.stephendiehl.com/hask/)

Use a sum type:

   data Datum = S String | D Double
   
   lst :: [Datum]
   lst = [S "a", D 3.14]
In Python we'd have to write the logic to handle both cases and fail with an exception or do an instanceof check. In Haskell we'd do this by pattern matching on the sum type.
   case (lst !! 42) of
      S n -> -- handle string
      D n -> -- handle number
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.