PureScript中<>运算符工作原理及代码类型匹配错误咨询
Hey there! Let's work through your PureScript questions—this stuff can feel confusing when you're starting out, so let's break it down clearly.
flip (\s -> show n <> s) 10 "Ten" throw a type error? First, let's fix a small implicit detail: your first example works because the lambda is capturing a variable n set to 10 somewhere, but the explicit, reusable version of this function is likely \n s -> show n <> s—a binary function that takes a showable value n and a string s, then returns their concatenation.
Now, let's recall what flip does: its type is flip :: forall a b c. (a -> b -> c) -> b -> a -> c. Plainly put, it takes a binary function f a b and returns a new function that swaps the order of its first two arguments: flip f b a = f a b.
- When you run
flip (\n s -> show n <> s) "Ten" 10, you're feeding the flipped function"Ten"(the originalsparameter) as the first argument, and10(the originalnparameter) as the second. This translates toshow 10 <> "Ten", which gives"10Ten"—that checks out. - When you try
flip (\n s -> show n <> s) 10 "Ten", you're passing10as the first argument to the flipped function. But the flipped function expects its first argument to be the originals—a String!10is an Int, not a String, so the type checker throws an error because it can't matchIntwithString(that's the "Could not match type I..." message you're seeing—short for "Int").
<> operator's exact behavior? The <> operator comes from PureScript's Semigroup type class. Its general type is:
(<>) :: forall a. Semigroup a => a -> a -> a
In simple terms, <> is a generic way to combine two values of the same type into another value of that same type. The exact behavior depends on the type's Semigroup instance:
- For
String,<>is string concatenation—so"foo" <> "bar"gives"foobar", which is exactly what's happening in your example (show nreturns a String, soshow n <> sjoins two strings). - For
List,<>appends two lists:[1,2] <> [3,4]becomes[1,2,3,4]. - For numeric types like
Int, there are multipleSemigroupinstances—one using addition (1 <> 2 = 3) and another using multiplication (1 <> 2 = 2), depending on which instance you import.
The hard rule: you can only use <> with two values of the same type, and that type must have a Semigroup instance defined. In your code, since both show n and s are Strings (which have a built-in Semigroup instance), the operator works as concatenation.
内容的提问来源于stack exchange,提问作者Angle.Bracket

