Data transfer through higher-order functions

I often had this problem in one form or another. Suppose I want to take the number x and apply a bunch of high-order functions for x, creating y. Then I check if y will satisfy a specific property, if so, then I want to return x.

This problem seems very complicated when I have a list of numbers [x1, x2..xn] and the functions that I use compact the list. For example, I apply a function to each of the elements in the list (creating [y1, y2 ..]), sort, group, and then I want to return the x values ​​for the largest group. For instance:

head . reverse . sort . map (length) . group . sort . map (mod 4) $ [1..10]

The answer is 6, but how would I rewrite such a function to tell me which elements with numbers from 1 to 10 belong to these 6?

I played with the idea of ​​passing tuples and used fst everywhere until snd was needed, or write a new class to make something like sorting work with only one element of the class, but I can't seem to come up with a clean approach

Thanks for the help.

+3
source share
2 answers

Here's a small set of code changes that return a value, not a length; the use of functions * Byavoids the need for tuples:

maximumBy (compare `on` length) . groupBy ((==) `on` mod 4) . sortBy (compare `on` mod 4) $ [1..10]

This code requires Data.List and Data.Function. Data.Function includes onthat allows you to compare (for sorting or grouping) any input function.

+5
source

GHC TransformListComp extension, .

{-# LANGUAGE TransformListComp #-}
import GHC.Exts

input = [1..10]
output = [ x
         | x <- input
         , let y = 4 `mod` x
         , then group by y
         , then sortWith by (-length x, the y)
         ]
-- output = [[5,6,7,8,9,10],[1,2,4],[3]]
+1

Source: https://habr.com/ru/post/1790259/


All Articles