Haskell - display odd allocated values ​​and evenly distributed values ​​in different ways

there is an easy way. To take a list of numbers, say 123456. Then multiply the odd number by three and the even number by 1.

i.e. (1 * 3) + (2 * 1) + (3 * 3) + (4 * 1) + (5 * 3) + (6 * 1)

I was thinking about a map function somewhere along the lines. But I do not know how to match * 3 with odd values. Oh, and if you could give me a non-prelude version that would be as big as the actual function or functions, as if it were imported from an external haskell file

thanks for the help

+5
source share
5 answers

, , zipWith (*) (cycle [3,1]) xs - , . , -, nitpick: , , 1 3 : -)

; xs be [9,8,7,3,2]. cycle [3,1] , , [3,1,3,1,3,1,..]. , zipWith f xs ys , head xs head ys f ( ) - f zipWith. xs ys , ; .

, (3 * 9), (1 * 8), (3 * 7), (1 * 3), (3 * 2) !

zipWith .

, " ", ​​ , . ...

+14

, xs - :

map (uncurry ($)) (zip (cycle [((*) 1), ((*) 3)]) xs)

:

[((*) 1), ((*) 3)] - , . ; .

cycle [...] , , [& times; 1, & times; 3, & times; 1, & times; 3...]

zip (cycle [...]) xs . , xs [1..6], [(& times; 1, 1), (& times; 3, 2), (& times; 1, 3), (& times; 3, 4), (& , 1, 5), (& times; 3, 6)].

$ :: (a -> b) -> a -> b ; a → b . , map (uncurry ($)) (zip ...) (, ) . uncurry, , ((a -> b), a) -> b.

; [1, 6, 3, 12, 5, 18].

+2

, , , , "" "" . , , , ...

import Data.List (mapAccumL)

yourFunc = snd . mapAccumL mult True -- 'True' represents an odd index, starting from 1
  where
    mult True  x = (False, 3 * x)
    mult False x = (True , x)
+1

, zip:

let list' = zip [1..] list
in map (\(cnt,val) -> if odd cnt then val * 3 else val) list'

, , . , , ( map), . , cycle zipWith, Haskell.

, .

0

, cycle zip. ( " " , , " - ".) :

  • ?
  • cycle ( )?

, , . , , Haskell, :

mult31 [] = 0
mult31 [x:x':xs] = x * 3 + x' * 1 + mult31 xs
mult31 [x] = x * 3

, , :

mult31 = m3
  where m3 (x:xs) = x * 3 + m1 xs
        m3 []     = 0
        m1 (x:xs) = x * 1 + m3 xs
        m1 []     = 0

Any of these features will seem less natural to a Haskell veteran than using a zip function with cycle, but for someone just starting out, it might be easier to follow.

0
source

All Articles