[Haskell-beginners] Using Functions with Fold

Francesco Ariis fa-ml at ariis.it
Mon Feb 1 05:07:32 UTC 2021


Il 31 gennaio 2021 alle 20:49 A. Mc. ha scritto:
> I feel like I need to go back to basics, so I've made a toy problem that
> takes a list of Ints, say [10, 20, 30, 40, 50, 60] and, in theory, iterates
> through the list in successive pairs i.e. [10, 20], [20, 30], [30, 40],
> [40, 50], [50, 60] and looks for a specific pair set, say 30, 40, and
> accumulates the number of times that pair appears in the list (for example
> purpose, there are no repeats, but assuming there were....).  What I've
> done is the following:
> 
> ---take starting at position 2, in increments of 2 with overlap allowed
> takeAtTwo :: [Int] -> Int -> [Int]
> takeAtTwo list position = take (2 + position) list
> 
> ---expects range of 0 to length list - 2
> grabTwo :: [Int] -> Int -> [Int]
> grabTwo list position = drop position (takeAtTwo list position)
> 
> -- and this does NOT work, half-pseudocode
> --- pass in a pair of Int, say [30, 40] and sum up the number of appearances
> numPair list = foldr (\pair acc -> if grabTwo list iterator == pair then
> acc + 1 else acc) 0
> 
> However, I am unsure how to get this to work properly with fold.
> Suggestions? Thanks in advance and thank you for your time.

You might have better luck with first generating the pairs and then
passing them to another function.

    λ> prova as = zip as (tail as)
    λ> prova [10,20..60]
    [(10,20),(20,30),(30,40),(40,50),(50,60)]

Counting now is a simple matter of

    λ> length . filter (==(30,40)) $ it
    1
    -- or use a fold if you prefer



More information about the Beginners mailing list