Lets say I have a Traversable
datum containing a handful of association pairs (Index, Fruit)
:
type Index = Int
data Fruit = Apple | Orange | Tomato
defaultFruit = Tomato
convertFruits :: (Traversable t) => t (Index, Fruit) -> Int -> [Fruit]
convertFruits input n = undefined
convertFruits
is supposed to return a list of length n
filled with Tomato
s, except for all places where the input
contained an association pair with a matching index — in which case the matching Fruit
from input
is placed at the matching index.
Examples of expected output:
convertFruits [] 4 = [Tomato, Tomato, Tomato, Tomato]
convertFruits [(2, Apple)] = [Tomato, Apple, Tomato, Tomato]
convertFruits [(1, Orange), (3, Orange), (4, Apple)] = \
[Orange, Tomato, Orange, Apple]
How can I define such a function? Can I code a pure approach efficiently, avoiding O(n²)?
I see that there's traverse
which takes Applicative
actions, and Applicative
looks a lot like Monad
. But in contrast to good ol' Monad
, I'm not really acquainted to Applicative
, practically speaking. Any help?
convertFruits [(2,Apple),(1,Orange),(2,Orange)] 4
should be[Tomato,Orange,Orange,Tomato]
? – Random Devt
any way, you don't needTraversable
:Foldable
should be enough. Or do you wantt (Index, Fruit) -> Int -> t Fruit
? Seeing your examples, both seem wrong, why don't you just useMap Index Fruit -> Int -> [Fruit]
? – leftaroundabout