Related
First of all, I want to say that I'm very very inexperienced with Haskell, and I know that I have done something (or multiple things) terribly wrong, been struggling for hours but I can't seem to find it.
power :: Int -> Int -> Int
power x y | y == 0 = 1
| x == 0 = 0
list = replicate y x
foldr (*) x list
main = print $ power 3 5
Error most of the time is either x and y not being passed to the replicate function or that foldr is a naked function, I understand what they both mean but have no idea on how I can pass the variables or come up with a solution.
You here created four functions: power, list, foldr and main. But you use variables x and y in the definition of the list function.
You can work with a where clause to specify subexpressions, for example:
power :: Int -> Int -> Int
power x y | y == 0 = 1
| x == 0 = 0
| otherwise = foldr (*) 1 list
where list = replicate y x
or perhaps more elegant with pattern matching:
power :: Int -> Int -> Int
power 0 _ = 0
power x y = foldr (*) 1 (replicate y x)
main = print $ power 3 5
Here we can also eliminate the case for x0, since our foldr starts working with 1, not x.
This algorithm is however not very efficient, since it is linear in the value of y. By checking recursively if the exponent is even or odd, you can make it faster. I leave this as an exercise.
You were very close! The main things that need to be fixed are:
When writing a definition with guards, the “fallback” case needs to be a guard as well, conventionally written with otherwise.
Recall that a definition without guards looks like this, with one left side (a name and parameter patterns/names) and one right side (an expression):
name patterns = expression
With guard conditions, there is one right-hand side for each guard:
name patterns | condition1 = expression1
| condition2 = expression2
…
| otherwise = expressionn
otherwise is really just an alias for True, that is, such a guard always matches. The only thing special about otherwise is that the compiler uses it as a hint when analysing whether a pattern match covers all possible cases.
In order to define a variable list, local to the definition of power, using the parameters x and y, you need to use either a let…in… expression, that is, let block in expression, or a where clause, equation where block. A block is a series of items (in this case, local definitions) which must all be written starting at the same column of indentation, or be delimited by explicit curly braces {…} and semicolons ;.
Using let…in… follows the structure of your original code pretty closely. I will adjust the indentation style to avoid needing to align anything, by putting a newline and a constant amount of indentation instead.
power :: Int -> Int -> Int
power x y
| y == 0 = 1
| x == 0 = 0
| otherwise = let
list = replicate y x
in foldr (*) x list
main :: IO ()
main = print $ power 3 5
Attaching a where clause to an equation is slightly more common than using a let…in… expression on the right side of an equation.
power :: Int -> Int -> Int
power x y
| y == 0 = 1
| x == 0 = 0
| otherwise = foldr (*) x list
where
list = replicate y x
main :: IO ()
main = print $ power 3 5
Note that in this case, there is a slight difference: the variable list is visible in all of the right-hand sides, although we only use it in one of them. With let list = … in e, list is only defined within e. In general, it’s helpful for readability to keep the scope of a variable as small as possible, although you can certainly go overboard:
a = …
where
b = …
where
c = …
where
d = …
-- If you see this much nesting, rethink!
If you run into issues with alignment and indentation, you can always use explicit delimiters instead. The code I wrote is equivalent to the following.
power :: Int -> Int -> Int; -- Begin ‘power’ signature.
power x y
| y == 0 = 1
| x == 0 = 0
| otherwise = let { -- Begin ‘let’ block.
list = replicate y x; -- End ‘list’ equation.
} in foldr (*) x list; -- End ‘let’ block, then end ‘power’ equation.
main :: IO (); -- Begin ‘main’ signature.
main = print $ power 3 5; -- End ‘main’ equation.
Or similarly with where { … }.
I am trying to build a function that converts a Decimal(Int) into a Binary number.
Unfortunately other than in java it is not possible to divide an int by two in haskell.
I am very new to functional programming so the problem could be something trivial.
So far I could not find another solution to this problem but
here is my first try :
fromDecimal :: Int -> [Int]
fromDecimal 0 = [0]
fromDecimal n = if (mod n 2 == 0) then
do
0:fromDecimal(n/2)
else
do
1:fromDecimal(n/2)
I got an java implementation here which I did before :
public void fromDecimal(int decimal){
for (int i=0;i<values.length;i++){
if(decimal % 2 = 0)
values[i]=true ;
decimal = decimal/ 2;
else {values[i]= false;
} }
}
Hopefully this is going to help to find a solution!
There are some problems with your solution. First of all, I advise not to use do at all, until you understand what do does. Here we do not need do at all.
Unfortunately other than in java it is not possible to divide an int by two in haskell.
It actually is, but the / operator (which is in fact the (/) function), has type (/) :: Fractional a => a -> a -> a. An Int is not Fractional. You can perform integer division with div :: Integral a => a -> a -> a.
So then the code looks like:
fromDecimal :: Int -> [Int]
fromDecimal 0 = [0]
fromDecimal n = if (mod n 2 == 0) then 0:fromDecimal (div n 2) else 1:fromDecimal (div n 2)
But we can definitely make this more elegant. mod n 2 can only result in two outcomes: 0 and 1, and these are exactly the ones that we use at the left side of the (:) operator.
So we do not need to use an if-then-else at all:
fromDecimal :: Int -> [Int]
fromDecimal 0 = [0]
fromDecimal n = mod n 2 : fromDecimal (div n 2)
Likely this is still not exactly what you want: here we write the binary value such that the last element, is the most significant one. This function will add a tailing zero, which does not make a semantical difference (due to that order), but it is not elegant either.
We can define an function go that omits this zero, if the given value is not zero, like:
fromDecimal :: Int -> [Int]
fromDecimal 0 = [0]
fromDecimal n = go n
where go 0 = []
go k = mod k 2 : go (div k 2)
If we however want to write the most significant bit first (so in the same order as we write decimal numbers), then we have to reverse the outcome. We can do this by making use of an accumulator:
fromDecimal :: Int -> [Int]
fromDecimal 0 = [0]
fromDecimal n = go n []
where go 0 r = r
go k rs = go (div k 2) (mod k 2:rs)
You cannot / integers in Haskell – division is not defined in terms of integral numbers! For integral division use div function, but in your case more suitable would be divMod that comes with mod gratis.
Also, you are going to get reversed output, so you can reverse manually it after that, or use more memory-efficient version with accumulator:
decToBin :: Int -> [Int]
decToBin = go [] where
go acc 0 = acc
go acc n = let (d, m) = n `divMod` 2 in go (m : acc) d
go will give you an empty list for 0. You may add it manually if the list is empty:
decToBin = (\l -> if null l then [0] else l) . go [] where ...
Think through how your algorithm will work. It starts from 2⁰, so it will generate bits backward from how we ordinarily think of them, i.e., least-significant bit first. Your algorithm can represent non-negative binary integers only.
fromDecimal :: Int -> [Int]
fromDecimal d | d < 0 = error "Must be non-negative"
| d == 0 = [0]
| otherwise = reverse (go d)
where go 0 = []
go d = d `rem` 2 : go (d `div` 2)
In Haskell, when we generate a list in reverse, go ahead and do so but then reverse the result at the end. The reason for this is consing up a list (gluing new items at the head with :) has a constant cost and the reverse at the end has a linear cost — but appending with ++ has a quadratic cost.
Common Haskell style is to have a private inner loop named go that the outer function applies when it’s happy with its arguments. The base case is to terminate with the empty list when d reaches zero. Otherwise, we take the current remainder modulo 2 and then proceed with d halved and truncated.
Without the special case for zero, fromDecimal 0 would be the empty list rather than [0].
The binary numbers are usually strings and not really used in calculations.
Strings are also less complicated.
The pattern of binary numbers is like any other. It repeats but at a faster clip.
Only a small set is necessary to generate up to 256 (0-255) binary numbers.
The pattern can systematically be expanded for more.
The starting pattern is 4, 0-3
bd = ["00","01","10","11"]
The function to combine them into larger numbers is
d2b n = head.drop n $ [ d++e++f++g | d <- bd, e <- bd, f <- bd, g <- bd]
d2b 125
"01111101"
If it's not obvious how to expand, then
bd = ["000","001","010","011","100","101","110","111"]
Will give you up to 4096 binary digits (0-4095). All else stays the same.
If it's not obvious, the db2 function uses 4 pairs of binary numbers so 4 of the set. (2^8) - 1 or (2^12) - 1 is how many you get.
By the way, list comprehension are sugar coated do structures.
Generate the above patterns with
[ a++b | a <- ["0","1"], b <- ["0","1"] ]
["00","01","10","11"]
and
[ a++b++c | a <- ["0","1"], b <- ["0","1"], c <- ["0","1"] ]
["000","001","010","011","100","101","110","111"]
More generally, one pattern and one function may serve the purpose
b2 = ["0","1"]
b4 = [ a++b++c++d | a <- b2, b <- b2, c <- b2, d <- b2]
b4
["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"]
bb n = head.drop n $ [ a++b++c++d | a <- b4, b <- b4, c <- b4, d <- b4]
bb 32768
"1000000000000000"
bb 65535
"1111111111111111"
To calculate binary from decimal directly in Haskell using subtraction
cvtd n (x:xs) | x>n = 0:(cvtd n xs)
| n>x = 1:(cvtd (n-x) xs)
| True = 1:[0|f<-xs]
Use any number of bits you want, for example 10 bits.
cvtd 639 [2^e|e<-[9,8..0]]
[1,0,0,1,1,1,1,1,1,1]
import Data.List
dec2bin x =
reverse $ binstr $ unfoldr ndiv x
where
binstr = map (\x -> "01" !! x)
exch (a,b) = (b,a)
ndiv n =
case n of
0 -> Nothing
_ -> Just $ exch $ divMod n 2
i just learned haskell yesterday and i'm stuck with a task.
i have a Matrix given; implemented with a function like this:
board 1 1 = 0
board 1 2 = 1
board 1 3 = 0
board 2 1 = 2
board 2 2 = 0
board 2 3 = 0
board 3 1 = 1
board 3 2 = 0
board 3 3 = 2
board _ _ = -1
Just that you have a little context:
that matrix is used for a minified sinking ships game.
so you would check an entry 2 1 like this
board 2 1
and get the respective result.
0 is a default value, -1 doesnt exist; 1 stands for a ship owned by player 1, the same goes with 2.
Now i have to write a function that just has to count the amount of ships owned by a specific player and it should return that amount.
e.g in that example board, the amount of 2's would be 2.
However, i have a restriction that i cant use anything related to lists.
I guess i have to work with recursion, and this is where i'm stuck.
i already have made a try with this:
(k is the player number and res should be the result.)
amountofships k board = rekurs 1 1 board res
where
res = 0
rekurs x y board res =
if (board x y == -1) then return(res)
else return(rekurs (x + 1) 1 board res)
where
new_rekurs a b board res2 =
if (board a b == -1) then return(res2)
else if (board a b == k) then return(new_rekurs a (b+1) board (res + 1))
else return(new_rekurs a (b+1) board res)
where
res2 = 0
Its meant to have a resursion function that goes through every column and inside that, it has another recursion function that would check every entry inside that column, return the amount, then check the next column, etc.
it doesnt compile and i dont think its an elegant approach, but I cant think of another one.
I would be thankful for any kind of help.
Edit : Thank you all for your answers. I see where the problem in my Code was.
I've used the structure proposed by Daniel, and it compiles at least:
amountofships k board = rekursColumn 1 1 0
where
rekursColumn x y res
| board x y = res
| otherwise = rekursColumn (x + 1) y (res + rowTotal)
where
rowTotal = rekursRow x y 0
rekursRow x y res
| board x y = res
| otherwise = rekursRow x (y + 1) (res + isOurBoat)
where
isOurBoat = if board x y == k then 1 else 0
I still get an Could not deduce (Num Bool) arising from the literal ‘1’
Error when calling
amountofships 1 example_board
. I guess this is because i didnt specify what the input types are? Specially since one parameter is actually a function.
Edit2: Oh i see where the problem was. I need to check if board x y == -1
my Code is working now:
amountofships :: Int -> (Int -> Int -> Int) -> Int
amountofships k board = rekursColumn 1 1 0
where
rekursColumn x y res
| board x y == -1 = res
| otherwise = rekursColumn (x + 1) y (res + rowTotal)
where
rowTotal = rekursRow x y 0
rekursRow x y res
| board x y == -1 = res
| otherwise = rekursRow x (y + 1) (res + isOurBoat)
where
isOurBoat = if board x y == k then 1 else 0
Thank you all for your help!
Okay, yes, you're a bit confused.
So my advice first is to try to straighten out what you want to do, in mostly English. I'm going to try to lead you to that without outright giving you the answer, since the point of this exercise is for you to learn more Haskell.
So it seems to me - though you haven't explained it - that what you intend to happen is:
amountofships calls internal function rekurs telling it to start at position 1 1 and passing it an accumulator argument that should start at 0
rekurs should examine the spot it's given, and if that spot is -1 say "oh, I'm off the grid, return the accumulator argument", and otherwise it should return the result of calling itself with one spot to the right.
Then you also somewhere define something called new_rekurs that you don't ever call.
So first let's try to fix your logic first, and then if you still have trouble translating that into Haskell we can work on that.
So the general pattern that you seem to be following is "call an internal tail-recursive function with an accumulator argument that checks "am I done yet?" and, if done, returns the accumulator argument. If not done, it computes the next place it should go and then calls itself on that."
Now, that's an okay pattern to use to solve this, but there are two problems with what you're doing:
You never add anything to the accumulator.
You need to travel in two dimensions.
So, traveling in two dimensions: there are two ways to do it. One is to keep a single function that keeps increasing x with each step until it gets to -1 and then increases y by 1 and reset x to 1. Another way - which I think in your case will be much, much easier - is to have two functions called rekursBoard and rekursRow (or whatever names you prefer) and the first function calls the second one to get the number of relevant ships in each row.
With the two-function solution, what you'd want to do is:
At the top level, call rekursBoard 1 1 0 (the arguments there are x, y, and res - note that you don't need to keep passing the board function on down to the inner functions)
In rekursBoard check if the given spot is off the board. If it is, the result is just res. If not, then the result is rekursBoard (x+1) y (res+rowTotal), where rowTotal is computed by calling rekursRow x y 0.
In rekursRow, check if the given spot is off the board. If it is, the result is just res. Otherwise, the result is rekursRow x (y+1) (res+isOurBoat), where isOurBoat is computed as 1 if the boat at spot x and y matches the k the top-level function was given, and 0 if not.
The overall structure of your function could look like this:
amountofships k board = -- .... some call here
where
rekursBoard x y res = -- ... some stuff here
where
rowTotal = -- ... some call here
rekursRow x y res = -- ... some stuff here
where
isOurBoat = -- ... something here
This isn't the only way to structure it, of course, it's just what I would do if I were writing up the answer sheet to this problem. Another very viable way to structure it is to make rekursRow something that's defined inside the where clause of rekursBoard and doesn't an x argument.
Now, a word in general on working in Haskell - Haskell has a function called return that means almost nothing like you expect. Seriously, at this early stage of learning Haskell, don't use return unless you're copying boilerplate code from the book. return DOES NOT DO WHAT YOU EXPECT. I personally think that the function is poorly named and that modern Haskell courses should avoid ever putting return on the page and instead use pure every place where they use return. (since on modern Haskell compilers, return and pure are the same thing for all the standard Monads)
Therefore, if you put return in your Haskell code for this problem, you will be sorry.
Don't do it.
Instead, get used to writing code like this:
countEmptySquare x y board = if board x y == 0 then 1 else 0
That is, just the form if someExpression then onePossibility else otherPossibility. No return statement, just bare expressions.
This will seem tedious at first, breaking down each calculation into named pieces, but it gets better. However, for laying out what's going on at an early level you should work through the careful break down.
First let me clean up that code of yours, syntactically:
amountofships :: ... -- Always write out type signatures!
amountofships k board = rekurs 1 1 board res
where res = 0
rekurs x y board res
| board x y == -1 = return res -- guards usually read nicer than `if`
| otherwise = return $ rekurs (x + 1) 1 board res
where new_rekurs a b board res2
| board a b == -1 = return res2 -- no need for parens around function arguments!
| board a b == k = return $ new_rekurs a (b+1) board (res + 1)
| otherwise = return $ new_rekurs a (b+1) board res
where res2 = 0
Now, a big problem here is return. Note that return in Haskell is very different from return in most other languages. It is not a keyword that's generally needed for the result of functions, instead, return is itself just a library function:
return :: Monad m => a -> m a
You need this to inject a value of “pure type” a, for example 3 :: Int, into the result of a monadic action of type m a, e.g. Just 3 :: Maybe Int. For example, you might use it thus:
-- Find the first even number in the tuple, if any
fstEven :: (Int, Int) -> Maybe Int
fstEven (a,b)
| even a = return a -- for the `Maybe` monad, this is the
| even b = return b -- same as writing `Just a` / `Just b`.
| otherwise = Nothing
Observe that I didn't write return Nothing: that would wrap the already monadic, empty value Nothing :: Maybe Int into another monadic layer, which is too much monad here.
Similar in your code: you wrap every result in return, but never unwrap anything.
Since in your case, everything is “pure” anyway, there's simply no need for that. To make something the result of a function, just write it out, like:
-- Use the first number in the tuple, if it's even; else use the second.
fstIfEven :: (Int, Int) -> Int
fstIfEven (a,b)
| even a = a
| otherwise = b
Or, in your case,
amountofships :: ... -- Always write out type signatures!
amountofships k board = rekurs 1 1 board res
where res = 0
rekurs x y board res
| board x y == -1 = res
| otherwise = rekurs (x + 1) 1 board res
where new_rekurs a b board res2
| board a b == -1 = res2
| board a b == k = new_rekurs a (b+1) board (res + 1)
| otherwise = new_rekurs a (b+1) board res
where res2 = 0
That looks better, but it doesn't work – here comes the interesting problem. See, you seem to not really think of recursion here. For a “recursive loop” in Haskell, you don't initialise a variable with something like res = 0 and then somehow change it in the course of the loop. Rather you straight up call the loop-body function with the initial value as the “front-end argument”, and then keep the function calling itself with other arguments. I'll demonstrate it for the simplified problem with only one grid-dimension. Instead of these magic numbers, I shall use descriptive tag types:
data Player = PlayerA | PlayerB
deriving (Eq, Show)
data BoardField = Coast | OpenSea | Ship Player
deriving (Eq, Show)
type Board = Int -> BoardField -- “array” of fields which may have ships in them, starting with index 0
amountOfShips :: Player -> Board -> Int
amountOfShips k board = go 0 0 -- the `board` is always the same, no need to pass
-- it explicitly to the worker-loop function `go`
where go x res = case board x of -- `case` is even better than guards, if all you're doing is equality comparison.
Coast -> res -- When we've reached the coast we're done, there can be no more ships.
Ship player
| player==k -> go (x+1) (res+1) -- Found ship of the requested player,
-- therefore continue recursion with incremented accumulator
_ -> go (x+1) res -- No ships here, so continue recusion with the same accumulator.
Im getting started to Haskell, and im trying to define the factorial function that takes one number and, if the number is negative, show nothing as result. Like this (just an example):
*Main> factorial 8
40320
*Main> factorial (-1)
*Main>
Is it possible, and how?
Thanks.
You can't do this with just a function, and it's probably not what you want anyhow. A function always has to return something, even if it's just a dummy value that represents not having a valid result! This is useful because it means the result of your function can always be used by other parts of your program—everything is more composable.
The usual idiomatic solution is to use the Maybe type, which lets you return either Just the result or Nothing:
factorial n | n < 0 = Nothing
| n < 2 = Just 1
| otherwise = ...
If you really want your behavior in GHCi, you can print out the result you want instead of returning it directly. This gives you more control over how the output looks, but it means you won't be able to reuse the result of your function directly. You can do it like this:
factorialPrint n | n < 0 = return () -- an IO action that does nothing
| otherwise = print (factorial n)
Instead of producing a result, this function produces an IO action. GHCi then executes this action and doesn't print anything itself, which means you have to print the result yourself explicitly.
If you want to keep it pure then you can do it by defining a new result type and defining show to convert to an empty string if the result is invalid:
data FactResult = R Integer | Invalid
instance Show FactResult where
show (R i) = show i
show Invalid = ""
factorial n | n < 0 = Invalid
factorial n = R $ product [1..n]
The "correct" way to do something like this would be to use Maybe.
factorial n
| n < 0 = Nothing
| n == 1 = Just 1
| otherwise = fmap (*n) $ factorial (n-1)
This outputs "Just n!" with an input of anything >= 0 and "Nothing" otherwise.
If you really want a blank response.
maybeStr Nothing = ""
maybeStr (Just x) = show x
Then to run print it you would say:
f = putStrLn . maybeStr . factorial
f 4 -- would print 24
f (-1) -- would print blank line
Yes this is possible, but we have to slightly change the factorial function:
fac :: Int -> IO ()
fac n
| n < 0 = return ()
| otherwise = print $ facHelp n
where
facHelp n = <your factorial function>
Now, in addition to the standard factorial, we check the input first and if the input is smaller than 0, we just return a thing called unit, which is nothing (to see at least). If the input is valid for the factorial, we will just print it normally.
I want to reverse an Integer in Haskell with recursion. I have a small issue.
Here is the code :
reverseInt :: Integer -> Integer
reverseInt n
| n>0 = (mod n 10)*10 + reverseInt(div n 10)
| otherwise = 0
Example 345
I use as input 345 and I want to output 543
In my program it will do....
reverseInt 345
345>0
mod 345 10 -> 5
reverseInt 34
34
34>0
mod 34 10 -> 4
reverseInt 3
3>0
mod 3 10 -> 3
reverseInt 0
0=0 (ends)
And at the end it returns the sum of them... 5+4+3 = 12.
So I want each time before it sums them, to multiple the sum * 10. So it will go...
5
5*10 + 4
54*10 + 3
543
Here's a relatively simple one:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = firstDigit + 10 * (reverseInt $ n - firstDigit * 10^place)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
firstDigit = n `div` 10^place
Basically,
You take the logBase 10 of your input integer, to give you in what place it is (10s, 100s, 1000s...)
Because the previous calculation gives you a floating point number, of which we do not need the decimals, we use the floor function to truncate everything after the decimal.
We determine the first digit of the number by doing n 'div' 10^place. For example, if we had 543, we'd find place to be 2, so firstDigit = 543/100 = 5 (integer division)
We use this value, and add it to 10 * the reverse of the 'rest' of the integer, in this case, 43.
Edit: Perhaps an even more concise and understandable version might be:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = mod n 10 * 10^place + reverseInt (div n 10)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
This time, instead of recursing through the first digit, we're recursing through the last one and using place to give it the right number of zeroes.
reverseInt :: Integer -> Integer
reverseInt n = snd $ rev n
where
rev x
| x>0 = let (a,b) = rev(div x 10)
in ((a*10), (mod x 10)*a + b)
| otherwise = (1,0)
Explanation left to reader :)
I don't know convenient way to found how many times you should multiply (mod n 10) on 10 in your 3rd line. I like solution with unfoldr more:
import Data.List
listify = unfoldr (\ x -> case x of
_ | x <= 0 -> Nothing
_ -> Just(mod x 10, div x 10) )
reverse_n n = foldl (\ acc x -> acc*10+x) 0 (listify n)
In listify function we generate list of numbers from integer in reverse order and after that we build result simple folding a list.
Or just convert it to a string, reverse it and convert it back to an integer:
reverseInt :: Integer -> Integer
reverseInt = read . reverse . show
More (not necessarily recursion based) answers for great good!
reverseInt 0 = 0
reverseInt x = foldl (\x y -> 10*x + y) 0 $ numToList x
where
numToList x = if x == 0 then [] else (x `rem` 10) : numToList (x `div` 10)
This is basically the concatenation of two functions : numToList (convert a given integer to a list 123 -> [1,2,3]) and listToNum (do the opposite).
The numToList function works by repeatedly getting the lowest unit of the number (using rem, Haskell's remainder function), and then chops it off (using div, Haskell's integer division function). Once the number is 0, the empty list is returned and the result concatenates into the final list. Keep in mind that this list is in reverse order!
The listToNum function (not seen) is quite a sexy piece of code:
foldl (\x y -> 10*x + y) 0 xs
This starts from the left and moves to the right, multiplying the current value at each step by 10 and then adding the next number to it.
I know the answer has already been given, but it's always nice to see alternative solutions :)
The first function is recursive to convert the integer to a list. It was originally reversing but the re-conversion function reversed easier so I took it out of the first. The functions can be run separately. The first outputs a tuple pair. The second takes a tuple pair. The second is not recursive nor did it need to be.
di 0 ls = (ls,sum ls); di n ls = di nn $ d:ls where (nn,d) = divMod n 10
di 3456789 []
([3,4,5,6,7,8,9],42)
rec (ls,n) = (sum [y*(10^x)|(x,y) <- zip [0..] ls ],n)
Run both as
rec $ di 3456789 []
(9876543,42)