Short form: is there a more idiomatic way to write (\a->[a])
?
Long form: For any data type Foo a
, if I have a function f :: Foo a -> b
and I need to write something like...
wrapAndF a = f $ Foo a
...I can make it point-free by writing
wrapAndF = f . Foo
But if my function g :: [a] -> b
operates on lists and my wrapper looks like this...
wrapAndG a = g [a]
...what is the most idiomatic way to write it point-free? I know I can write an explicit lambda:
wrapAndG = g . (\x->[x])
or, mirroring the use of the constructor in the Foo example, use the list constructor (:)
, but then I have to flip the arguments:
wrapAndG = g . flip (:) []
...but what is the idiomatic way to refer to the singleton list constructor function? I expected to find a standard function with signature a -> [a]
, but I couldn't find it on Hoogle or Data.List.
There is of course the alternative of simply not writing it point-free (and that is certainly a valid answer) but since passing type constructors around as wrapper functions seems really useful, it felt odd that I couldn't find a standard function to wrap a value into a list, so I figured I may be missing something.
The list-singleton is a Haskell package allows you to easily and clearly create lists with only one element in them, which are typically called "singleton lists" or simply "singletons".
() is very often used as the result of something that has no interesting result. For example, an IO action that is supposed to perform some I/O and terminate without producing a result will typically have type IO () .
The singletonList() method of java.util.Collections class is used to return an immutable list containing only the specified object. The returned list is serializable. Syntax: Parameters: This method takes the object o as a parameter to be stored in the returned list.
What is a Singleton and an object (in Kotlin)? The singleton pattern restricts the instantiation of a class to a single object. It is useful in cases wherein you only need a single object to contain a global state. Access is through static methods that ensures a single instance
There are two types of singleton implementations: eager and lazy initialization. They differ in the way they initialize the singleton instance. We must also consider thread-safety in each of them.
This list will always contain only one element thus the name singleton list. When we try to add/remove an element on the returned singleton list, it would give UnsupportedOperationException. Attention reader! Don’t stop learning now.
Echoing the comments by user2407038 and chi, (:[])
is a fine way of spelling it if you want something specific to lists:
wrapAndG = g . (:[])
For lists pure
does what you want:
wrapAndG = g . pure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With