2
votes

Disclaimer: I'm new to purescript and have yet to grok the amazing but somewhat overwhelming type system.

Say I want a function which ignores its argument and always returns the same value. Defining this manually as an anonymous function is not a problem:

(\_ -> 42) <$> [true, false]
-- => [42, 42]

But I wondered whether there's a more idiomatic (and concise) way of doing this. Data.Const might be involved, but I have yet to figure out how to use it for this. Something like (getConst 42) <$> [true, false] does not work.

edit: Defining this myself:

makeConst :: forall a b. a -> (b -> a)
makeConst x = (\_ -> x)

(makeConst 42) <$> [true, false]
-- => [42, 42]

This works fine, but I wouldn't be surprised if something like that exists in the standard modules and I simply didn't see it...

1
I think you want the const function: (const 42) <$> [true, false] - Lee
Yup, that's it. Guess I should have read the Prelude functions before posting this. Mind making this an answer so I can accept it? - Aljoscha Meyer
FYI in your specific example of const 42 <$> [true, false] there are the <$ and $> combinators from Data.Functor in purescript-control. Used as such: 42 <$ [true, false] and [true, false] $> 42. Reference: pursuit.purescript.org/packages/purescript-control/0.3.2/docs/… - LiamGoodacre

1 Answers

3
votes

You want the const function

const :: forall a b. a -> b -> a

which you can use to create your function:

(const 42) <$> [true, false]