I'm writing my homework (CIS194 Haskell course).
I must rewrite the following recursive function to pipeline functions (without obvious recursion).
fun2 :: Integer -> Integer
fun2 1 = 0
fun2 n
| even n = n + fun2 ( n ‘div‘ 2 )
| otherwise = fun2 (3 * n + 1)
My first try is here:
fun2''' = sum
. (filter (even))
. unfoldr (\x -> if (even x)
then Just (x, x `div` 2)
else if (x==1) then Nothing
else Just (x, x * 3 + 1))
Is this a normal solution or is it weird?
And how can I rewrite fun2 better?
Now i try write version with takeWhile and iterate
my 2nd try:
fun2'' :: Integer -> Integer
fun2'' = sum
. (filter even)
. takeWhile (/=1)
. iterate (\x -> if even x
then x `div` 2
else x * 3 + 1 )
i have little problems with until version now.
Looks not bad, the only thing here that's a bit of a red flag in Haskell is else if. In this case, it can be rewritten nicely in applicative style:
{-# LANGUAGE TupleSections #-}
import Control.Applicative
import Control.Monad (guard)
fun2''' = sum
. filter even
. unfoldr ( \x -> fmap (x,) $
x`div`2 <$ guard(even x)
<|> x*3 + 1 <$ guard( x/=1 )
)
Nested ifs can now be written with multi-way IF:
g :: Integer -> Integer
g = sum .
unfoldr (\x->
if | even x -> Just (x, x `div` 2)
| x==1 -> Nothing
| otherwise -> Just (0, x * 3 + 1))
Or you can define your own if operator,
(??) t (c,a) | t = c | otherwise = a
g = sum . unfoldr (\x-> even x ?? (Just (x, x `div` 2) ,
(x==1) ?? (Nothing, Just (0, x * 3 + 1))))
Same function with until, with sum and filter fused into it:
g = fst . until ((==1).snd)
(\(s,n) -> if even n then (s+n,n`div`2) else (s,3*n+1))
. ((,)0)
or
g = sum . filter even . f
f :: Integer -> [Integer]
f = (1:) . fst . until ((==1).snd)
(\(s,n) -> if even n then (n:s,n`div`2) else (n:s,3*n+1))
. ((,)[])
The last function, f, shows the whole Collatz sequence for a given input number, reversed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With