Standard ML Foldl/Foldr function with multiplication operator? - whitespace

For Standard ML (SMLNJ), for the foldr and foldl functions, what is the correct way to use the multiplication operator?
Using foldr (op *) 1 [1,2,3]; gives an error
Standard ML of New Jersey v110.78 [built: Thu Aug 31 03:45:42 2017]
stdIn:1.12 Error: unmatched close comment
stdIn:1.9-1.18 Error: syntax error: deleting OP INT LBRACKET
It appears that the * has other overloads.

Whitespace normally doesn't matter for SMLNJ. But for the multiplication (asterisk) operation it does.
Make sure you have a space between the asterisk and the closing parenthesis * ) or it will be interpreted as an unopened comment *).
foldr (op * ) 1 [1,2,3];

Related

What does an 'at' # sign mean in Julia?

For example, here:
ys = lift(frequency, phase) do fr, ph
#. 0.3 * sin(fr * xs - ph)
end
from here.
I am failing to interpret it as a macro definition or call.
TLDR: # invokes a macro. https://docs.julialang.org/en/v1/manual/metaprogramming/
One of julia's best features in my opinion are it's macros. They allow you to easily write functions that manipulate source code. #. for example turns 0.3 * sin(fr * xs - ph) into 0.3 .* sin(fr .* xs - ph). Another common example is #time which roughly would translate the same expression to
t1=time()
0.3 * sin(fr * xs - ph)
println(time()-t1)
Note that neither of these are achievable by a function, since functions have their inputs evaluated before they run, while macros instead operate on the code itself.
I think it is worth to add that it is easy to learn what #. does by invoking help. Press ? then write #. and hit enter to get:
help?> #.
#. expr
Convert every function call or operator in expr into a "dot call" (e.g.
convert f(x) to f.(x)), and convert every assignment in expr to a "dot
assignment" (e.g. convert += to .+=).
If you want to avoid adding dots for selected function calls in expr, splice
those function calls in with $. For example, #. sqrt(abs($sort(x))) is
equivalent to sqrt.(abs.(sort(x))) (no dot for sort).
(#. is equivalent to a call to #__dot__.)
Examples
≡≡≡≡≡≡≡≡≡≡
julia> x = 1.0:3.0; y = similar(x);
julia> #. y = x + 3 * sin(x)
3-element Array{Float64,1}:
3.5244129544236893
4.727892280477045
3.4233600241796016
where you also learn that #. is just a shorthand for #__dot__.
And if you want to find its definition write e.g.:
julia> #which #. 1
#__dot__(__source__::LineNumberNode, __module__::Module, x) in Base.Broadcast at broadcast.jl:1241
to get the exact information on location of its implementation or write #edit #. 1 and it will get opened-up in your editor.
Above I have commented on how to learn what #. does and how it is implemented. If you want to learn what is the effect of #. (or any macro in general) you can use the #macroexpand macro. Therefore if you write e.g.:
julia> #macroexpand #. coalesce(sin(#view x[:, 1]), 0.0)
:(coalesce.(sin.(true && (view)(x, :, 1)), 0.0))
you can see how #. macro rewrites your original expression coalesce(sin(x), 0.0). Note that in this case the expressions are not evaluated - you only get an equivalent expression with all macros removed.
If you wanted to see only #. macro expanded (assuming - as in an example above it is the outermost macro) then use:
julia> #macroexpand1 #. coalesce(sin(#view x[:, 1]), 0.0)
:(coalesce.(sin.(#= REPL[11]:1 =# #view(x[:, 1])), 0.0))
As you can see #macroexpand1 is not recursive and only expanded the outermost macro and left #view macro untouched.

evaluation post-fix with pushing operands into the stack

Not sure how to start this off, any suggestions?
Define a SCHEME function, named (eval-postfix p), that will take postfix expression (stored in a list of integers representing operands and characters representing operators), evaluate that expression, and return the result.
Your function should support the operations of addition (#+), subtraction (#-), multiplication (#*), divi- sion(#/), and exponentiation(#\ˆ).
You may want to work incrementally by starting with a function that takes a character representing an operator and can pop two operands off of a stack, evaluate the operator and push the result back on the stack. Next you can add a function that evaluates a postfix expression by pushing operands onto the stack and evaluating operators when encountered. Note, you may want to use the number? function to determine whether an item in the list is an operand or an operator.
Make a function that executes a single instruction on a stack, and returns the changed stack:
(define (postfix-execute-one instruction stack)
...)
it should check if instruction is number? or a symbol like '+. If it's a number you can just return (cons instruction stack) to push it, if it's an operator you need to pop 2 items off the stack, add them (or subtract them) and then push that on the stack and return.
Then you can make
(define (postfix-execute-all instructions stack)
...)
which recursively loops over the list of instructions, executing each one using the helper function defined earlier, until it reaches null?. Then it can return the final stack.
This is the suggested starting point from your description spelled out in more detail.
It's a good starting point, so stick to it.
Write a function whose input is one operator and a stack:
operator: +
stack: |x y z w|
It should pop two operands:
operator: +
left operand: x
right operand: y
stack: |z w|
evaluate:
result: x + y = A
stack: |z w|
and return the stack with the result added on top:
|A z w|
When you're done with that (make sure you test with all five operators) you use this function to implement the full evaluation function.

F# discriminated union syntax clarification

I'm reading Expert F# 4.0 and at some point (p.93) the following syntax is introduced for list:
type 'T list =
| ([])
| (::) of 'T * 'T list
Although I understand conceptually what's going on here, I do not understand the syntax. Apparently you can put [] or :: between parentheses and they mean something special.
Other symbols aren't allowed, for example (++) or (||). So what's going on here?
And another thing is the 'operator' nature of (::). Suppose I have the following (weird) type:
type 'T X =
| None
| Some of 'T * 'T X
| (::) of 'T * 'T X
Now I can say:
let x: X<string> = Some ("", None)
but these aren't allowed:
let x: X<string> = :: ("", None)
let x: X<string> = (::) ("", None)
So (::) is actually something completely different than Some, although both are cases in a discriminated union.
Theoretically, F# spec (see section 8.5) says that union case identifiers must be alphanumeric sequences starting with an upper-case letter.
However, this way of defining list cons is an ML idiomatic thing. There would be riots in the streets if we were forced to write Cons (x, Cons(y, Cons (z, Empty))) instead of x :: y :: z :: [].
So an exception was made for just these two identifiers - ([]) and (::). You can use these, but only these two. Besides these two, only capitalized alphanumeric names are allowed.
However, you can define free-standing functions with these funny names:
let (++) a b = a * b
These functions are usually called "operators" and can be called via infix notation:
let x = 5 ++ 6 // x = 30
As opposed to regular functions that only support prefix notation - i.e. f 5 6.
There is a separate quite intricate set of rules about which characters are allowed in operators, which can be only unary, which can be only binary, which can be both, and how they define the resulting operator precedence. See section 4.1 of the spec or here for full reference.

SML| foldl with if

I'm having this exercise which asks to count how many values in a boolean list are true.
I typed this:
fun countt xs = foldl (fn (x,y) => if x=true then y=y+1) 0 xs;
which, apparently, is wrong. I'm getting the following error:
stdIn:54.21-54.24 Error: syntax error: deleting RPAREN INT0
Now, I've searched a bit and found out that RPAREN is a Syntax error. But i can't figure why there's a problem in the first place.
In a functional programming language, an if expression must have both then branch and an else branch (and they must both have the same type).
Your if expression only has a then branch.
Additionally, x=true always evaluates to the same value as x so you can just write if x then ... else ....
Finally, it looks like you're trying to write an assignment in the then branch. Remember that a foldl works by repeatedly passing the accumulator (y) to the function as it traverses the list with xs. So if you want to update the accumulator, all you have to do is return the updated value.
Just to complement the previous answer here are the suggested modifications:
fun countt xs = foldl (fn (x,acc) => if x then acc+1 else acc) 0 xs;
The term in parenthesis is the first argument to foldl, the value 0 is the seed value and the xs is the sequence that will be folded. The function takes a value and the current element of the sequence xs.
The function must return a value of the same type of 0, an integer.

Palindrome Golf

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python:
R=lambda s:all(a==b for a,b in zip(s,reversed(s)))
50 characters.
The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.
7 characters in J: Not sure if this is the best way, I'm somewhat new to J :)
p=:-:|.
explanation: |. reverses the input. -: compares. the operands are implicit.
p 'radar'
1
p 'moose'
0
Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.
p
Edit: Less flippant version (i386 asm, AT&T syntax)
xor %eax, %eax
mov %esi, %edi
#cld not necessary, assume DF=0 as per x86 ABI
repne scasb
scan:
dec %edi
cmpsb
.byte 0x75, 6 #jnz (short) done
dec %edi
cmp %esi, %edi
.byte 0x72, -9 #jb (short) scan
inc %eax
done:
16 bytes, string pointer goes in ESI, result is in EAX.
Sadly, I'm unable to get under a thousand words...
(LabVIEW. Yeah, they'll let just about any hobo post here ;)
Haskell, 15 chars:
p=ap(==)reverse
More readable version, 16 chars:
p x=x==reverse x
Another python version that is rather shorter (21 chars):
R=lambda s:s==s[::-1]
At the risk of getting down votes, most all of these just call a command reverse of some sort that hides all the real programming logic.
I wonder what the shortest manual way to do this is in each of these languages.
With C# and LINQ operators:
public bool IsPalindrome(string s)
{
return s.Reverse().SequenceEqual(s);
}
If you consider Reverse as cheating, you can do the entire thing with a reduction:
public bool IsPalindrome(string s)
{
return s.Aggregate(new StringBuilder(),
(sb, c) => sb.Insert(0, c),
(sb) => sb.ToString() == s);
}
Perl (27 chars):
sub p{$_[0]eq reverse$_[0]}
Ruby (24 chars):
def p(a)a==a.reverse end
73 clean, readable, chars written in java
boolean p(String s){return s.equals(""+new StringBuffer(s).reverse());}
peace :)
Pointless Haskell version (15 chars, though doesn't really work unless you include Control.Arrow and Control.Monad and ignore the monomorphism restriction):
p=ap(==)reverse
Lua aims more at readability than conciseness, yet does an honest 37 chars:
function p(s)return s==s:reverse()end
variant, just for fun (same size):
p=function(s)return s==s:reverse''end
The JavaScript version is more verbose (55 chars), because it doesn't has a string reverse function:
function p(s){return s==s.split('').reverse().join('')}
(equal p (reverse p))
lisp. 18 characters.
ok, this is a special case. This would work if typed directly into a lisp interpreter and p was already defined.
otherwise, this would be necessary:
(defun g () (equal p (reverse p)))
28 characters.
I'll take it a little bit further: full c code, compile and go.
90 characters
main(int n,char**v){char*b,*e;b=e=v[1];while(*++e);for(e--;*b==*e&&b++<e--;);return b>e;}
F# (a lot like the C# example)
let p s=let i=0;let l=s.Length;while(++i<l)if(s[i]!=[l-i-1]) 0; 1;;
PHP:
function p($s){return $s==strrev($s);} // 38 chars
or, just
$s==strrev($s); // 15 chars
Isn't using the reverse function in your language kind of cheating a bit? I mean, looking at the Ruby solution give as
def p(a)a==a.reverse end
you could easily rewrite that as
def p(a)a==a.r end
and just say that you made an extension method in your code so that "r" called reverse. I'd like to see people post solutions that don't contain calls to other functions. Of course, the string length function should be permitted.
Ruby without reverse - 41 characters
def m(a)a==a.split('').inject{|r,l|l+r}end
VB.Net - 173 Chars
Function P(ByVal S As String) As Boolean
For i As Integer = 0 To S.Length - 1
If S(i) <> S(S.Length - i - 1) Then
Return False
End If
Next
Return True
End Function
Golfscript, 5 char
.-1%=
$ echo -n abacaba | ruby golfscript.rb palindrome.gs
1
$ echo -n deadbeef | ruby golfscript.rb palindrome.gs
0
Common Lisp, short-and-cheating version (23 chars):
#L(equal !1(reverse !1))
#L is a reader macro character implemented by SHARPL-READER in the iterate package. It's basically equivalent to (lambda (!1) ...).
Common Lisp, long version using only primitives (137 including whitespace, compressible down to 108):
(defun p (s)
(let ((l (1- (length s))))
(iter (for i from l downto (/ l 2))
(always (equal (elt s i) (elt s (- l i)))))))
Again, it uses iterate, which is basically a cleaner version of the builtin LOOP facility, so I tend to treat it as being in the core language.
Not the shortest, and very after-the-fact, but I couldn't help giving it a try in MATLAB:
R=#(s)all(s==fliplr(s));
24 chars.
C# Without Reverse Function 84 chars
int p(char[]s){int i=0,l=s.Length,t=1;while(++i<l)if(s[i]!=s[l-i-1])t&=0;return t;}
C# Without Reverse Function 86 chars
int p(char[]s){int i=0;int l=s.Length;while(++i<l)if(s[i]!=s[l-i-1])return 0;return 1;}
VBScript 41 chars
function p:p=s=strreverse(s):end function
18 character perl regex
/^(.?|(.)(?1)\2)$/
52 characters in C, with the caveat that up to half the string will be overwritten:
p(char*s){return!*s||!(s[strlen(s)-1]-=*s)&&p(++s);}
Without library calls it's 64 characters:
p(char*s){char*e=s;while(*e)++e;return!*s||!(*--e-=*s)&&p(++s);}
Inspired by previous post, 69 characters
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++!=*--b;return!q;}
EDIT: Down one char:
p(char*a){char*b=a,q=0;while(*++b);while(*a)q|=*a++%*--b;return!q;}
EDIT2: 65 chars:
p(char*a){char*b=a;while(*b)b++;while(*a&&*a++==*--b);return!*a;}
Haskell, 28 chars, needs Control.Arrow imported.
p=uncurry(==).(id&&&reverse)
Straightforward implementation in C using standard library functions, inspired by the strlen in the other C answer.
Number of characters: 57
p(char*s){char*r=strdup(s);strrev(r);return strcmp(r,s);}
Confession: I'm being the bad guy by not freeing r here. My current attempt at being good:
p(char*s){char*r=strdup(s);s[0]=strcmp(strrev(r),s);free(r);return s[0];}
brings it to 73 characters; I'm thinking of any ways to do it shorter.
Clojure using 37 characters:
user=> (defn p[s](=(seq s)(reverse(seq s))))
#'user/p
user=> (p "radar")
true
user=> (p "moose")
false
24 characters in Perl.
sub p{$_[0]eq+reverse#_}
Groovy 17B:
p={it==it[-1..0]}
Downside is that it doesn't work with emptry string.
On second thought, throwing exception for empty string is reasonable since you can't tell if nothing is palindrome or not.
Without using any library functions (because you should really add in the #include cost as well), here's a C++ version in 96:
int p(char*a,char*b=0,char*c=0){return c?b<a||p(a+1,--b,c)&&*a==*b:b&&*b?p(a,b+1):p(a,b?b:a,b);}
My attempt in C (70 chars):
P(char*s){char*e=s+strlen(s)-1;while(s<e&&*s==*e)s++,e--;return s>=e;}
[Edit] Now actually working
[Edit 2] Reduced from 74 to 70 by using default int return
In response to some of the comments: I'm not sure if that preprocessor abuse counts - you could just define the whole thing on the command line and make the function one character.

Resources