Adding two functions together in Haskell

后端 未结 3 1625
刺人心
刺人心 2021-01-17 02:04

Hi I am new in Haskell and I came across an interesting problem but I was not really sure on how I would go about solving it. I am about to show you only two parts of the qu

3条回答
  •  无人共我
    2021-01-17 02:16

    First, you need a way to break some large number into digits.

    digits :: Integral x => x -> [x]
    digits 0 = []
    digits x = digits (x `div` 10) ++ [x `mod` 10]
    

    Which gives you...

    Prelude> digits 12345
    [1,2,3,4,5]
    

    You can then drop the last digit with init

    Prelude> (init . digits) 12345
    [1,2,3,4]
    

    The a helper function to map over odd elements in a list.

    mapOdd _ [] = []
    mapOdd f (x:[]) = [f x]
    mapOdd f (x:y:rest) = f x : y : mapOdd f rest
    

    Giving you...

    Prelude> mapOdd (+10) [1..10]
    [11,2,13,4,15,6,17,8,19,10]
    

    And a function to get back to a large number...

    undigits = sum . zipWith (*) [10^n | n <- [0..]] . reverse
    

    Resulting in...

    Prelude> undigits [1, 2, 3, 4]
    1234
    

    And putting it all together

    Prelude> undigits . mapOdd (*2) . init . digits $ 12345
    2264
    

    In functional languages particularly, always try to solve a problem by composing solutions to smaller problems :)

提交回复
热议问题