I want to use Haskell to solve a financial combinatorial problem, the list monad seems to be a good fit for this.
Now, my problem with the list monad is its inability to give names to the values involved. I will try to exemplify:
loan = [1000*x | x <- [1..3]]
interest_rate = [0.005*x | x <- [4..10]]
calc = do
l <- loan
i <- interest_rate
return (l*i)
Running calc above gives me a list of numbers ([20.0,25.0,30.0,35.0,40.0, ... ]), but I can’t tell what the loan and interest rate is used for each calculation.
I get lost here, my intuition tells me to create my own monadic type of, say HelpfulNumber :: (String,[Double]) and somehow say that:
>>= and return should be >>= . snd and return . snd
Am I on the right course here, or is there a better way? I am feeling a bit lost to be honest.
You could use a record type to make your output clearer:
Use
printloans loansorprintloans loans'at the ghci prompt.Edit: I forgot to include the definition of
dp. It’s for rounding to a given number of decimal places:Here’s a way using a list directly:
But if you like the monadic style, you can use:
which benefits from fewer commas, and it’s easier to change the order of the
<-lines to change the order of the answers.You can add extras to your
Loanrecord and calculate with them.You get output like this:
EDIT:
You told me elsewhere you’d like output like
ir_5% yrs_3 amt_4000 tot_4360.5. It’s uglier, but here’s a way of doing that sort of thing:When you do
mapM_ putStrLn loans''you get output likebut I think the record type is much nicer – its output is easier to read and there’s less messing about with strings.