Haskell Prelude에서 'const'의 요점은 무엇입니까?
Haskell Prelude를 살펴보면 다음과 같은 기능이 있습니다 const
.
const x _ = x
이 기능과 관련된 어떤 것도 찾을 수없는 것 같습니다.
점은 무엇인가? 누구든지이 기능이 어디에서 사용될 수 있는지 예를 들어 줄 수 있습니까?
유연성이 모두 필요하지 않을 때 고차 함수로 전달하는 데 유용합니다. 예를 들어, 모나드 시퀀스 연산자 >>
는 모나 딕 바인드 연산자 측면에서 다음과 같이 정의 할 수 있습니다.
x >> y = x >>= const y
람다를 사용하는 것보다 다소 깔끔합니다.
x >> y = x >>= \_ -> y
포인트없이 사용할 수도 있습니다.
(>>) = (. const) . (>>=)
이 경우 특별히 권장하지는 않지만.
HAMMAR의 우수한 직접 대답에 추가하려면 겸손 기능이 좋아 const
하고 id
그들이 것과 같은 이유로 고차 함수로 정말 유용한 기본적인 에서 스키 콤비 미적분학 .
하스켈의 전주곡 기능이 그 공식적인 시스템이나 그 무엇이든 의식적으로 모델화되었다고 생각하지 않습니다. 하스켈에서 풍부한 추상화를 만드는 것은 매우 쉽습니다. 따라서 이러한 유형의 이론적 인 것이 실제로 유용하게 나타나는 것을 종종 볼 수 있습니다.
뻔뻔한 플러그,하지만 난에 대한 실용적 인스턴스 방법에 대해 블로그에 (->)
실제로있는 S
및 K
연결자 여기 가 당신이에있어 물건의 종류의 경우.
사용에 대한 간단한 예 const
는 Data.Functor.(<$)
. 이 함수를 사용하면 다음과 같이 말할 수 있습니다. 여기에 지루한 무언가가있는 펑터가 있지만 대신 펑터의 모양을 변경하지 않고 다른 흥미로운 것을 포함하고 싶습니다. 예
import Data.Functor
42 <$ Just "boring"
--> Just 42
42 <$ Nothing
--> Nothing
"cool" <$ ["nonsense","stupid","uninteresting"]
--> ["cool","cool","cool"]
정의는 다음과 같습니다.
(<$) :: a -> f b -> f a
(<$) = fmap . const
또는 무의미하게 작성되지 않았습니다.
cool <$ uncool = fmap (const cool) uncool
const
여기에서 입력에 대해 "잊기"위해 사용되는 방법을 볼 수 있습니다 .
이 기능과 관련된 어떤 것도 찾을 수없는 것 같습니다.
다른 많은 답변은 상대적으로 난해한 (적어도 신규 사용자에게는) const
. 다음은 간단한 것입니다. const
두 개의 인수를 취하고 첫 번째 인수를 버리지 만 두 번째 인수에서 흥미로운 일을하는 람다를 제거하는 데 사용할 수 있습니다 .
예를 들어 다음과 같은 (비효율적입니다!) length
,
length' = foldr (\_ acc -> 1 + acc) 0
다음과 같이 다시 작성할 수 있습니다.
length' = foldr (const (1+)) 0
which is perhaps more elegant.
The expression const (1+)
is indeed semantically equivalent to \_ acc -> 1 + acc
, because it takes one argument, throws it away, and returns the section (1+)
.
Another use is to implement class member functions that have a dummy argument which should not be evaluated (used to resolve ambiguous types). Example that could be in Data.bits:
instance Bits Int where
isSigned = const True
bitSize = const wordSize
...
By using const we explicitly say that we are defining constant values.
Personally I dislike the use of dummy parameters, but if they are used in a class then this is a rather nice way of writing instances.
const
may be just the implementation you are looking for in conjunction with other functions. Here is an example I discovered.
Say we want to rewrite a structure of 2-tuples to another structure of 2-tuples. I might express this as so:
((a,b),(c,d)) ⇒ (a,(c,(5,a)))
I can give a straight-forward definition with pattern matching:
f ((a,b),(c,d)) = (a,(c,(5,a)))
What if I want a pointless (tacit) solution for these kind of rewrites? Some thinking and fiddling later, the answer is that we can express any rewrites with (&&&), const, (.), fst, snd
. Note that (&&&)
is from Control.Arrow
.
The solution of the example using these functions is:
(fst.fst &&& (fst.snd &&& (const 5 &&& fst.fst)))
Note the similarity with (a,(c,(5,a)))
. What if we replace &&&
with ,
? Then it reads:
(fst.fst, (fst.snd, (const 5, fst.fst)))
Notice how a
is the first element of the first element, and that is what fst.fst
projects. Notice how c
is the first element of the second element, and that is what fst.snd
projects. That is, variables become the path to their source.
const
allows us to introduce constants. Interesting how the name lines up with the meaning!
I then generalised this idea with Applicative so that you can write any function in a pointless style (so long as you have case analysis available as functions, such as maybe
, either
, bool
). Again, const
plays the role of introducing constants. You can see this work in the Data.Function.Tacit package.
When you start abstractly, at the goal, and then work towards an implementation, you can be surprised by the answers. That is to say, any one function may be as mysterious as any one cog in a machine. If you pull back to bring the whole machine into view, however, you can understand the context in which that cog is necessary.
Say you want to create a list of Nothings
equal to the length of a string. As const
returns its first argument, no matter the second, you can do:
listOfNothings :: String -> [Maybe Char]
listOfNothings = (map . const) Nothing
or, more explicitly:
listOfNothing st = map (const Nothing) st
참고URL : https://stackoverflow.com/questions/7402528/whats-the-point-of-const-in-the-haskell-prelude
'programing tip' 카테고리의 다른 글
다음과 유사한 삼항 연산자? : (0) | 2020.09.14 |
---|---|
데이터가 추가 될 때 div 끝으로 자동 스크롤하는 방법은 무엇입니까? (0) | 2020.09.14 |
Mac OS X에서 프로젝트를 컴파일 할 때 시스템 키 체인을 사용하려고합니다. (0) | 2020.09.13 |
HTML을 다른 창이나 탭에서 하이퍼 링크로 여는 방법은 무엇입니까? (0) | 2020.09.13 |
존재하지 않는 경우에만 mkdir (0) | 2020.09.13 |