fun insert R x [] acc = [x]
| insert R x (h::t) acc =
if R (x,h) then acc::(x::(h::t))
else(
acc=acc::h;
insert R x t acc
);
fun isort_aux R [] acc = acc
| isort_aux R (x::xs) acc =
isort_aux xs (insert R x acc [])
fun isort_2 R xs = isort_aux R xs []
I am trying to write a tail recursive code for insertion sort in sml for which i made a accumulator 'acc' but in line 5 acc=acc::h is giving the following error
Standard ML of New Jersey v110.78 [built: Thu Aug 31 03:45:42 2017]
- stdIn:5.3-5.13 Error: operator and operand don't agree [circularity]
operator domain: 'Z * 'Z list
operand: 'Z * 'Z
in expression:
acc :: h
-
acc=acc::h;
insert R x t acc
Having two calls here doesn't work in SML. You can only do one thing in SML because of the way the language is structured. I did this when starting out on SML a few weeks ago and it didn't work for me.
As the comment by #moldbnilo said your code is trying to compare acc to acc::h and not setting it equal to acc.
I am very new to SML so take this with a grain of salt as it may not be right.
Related
semOp l = \m -> case l of
LD g -> case m of
St xs -> St (g::xs)
_ -> Error
Just want to know what does the \m part is doing here.
\m -> ... is syntax for anonymous function, aka "lambda-expression".
For example, the following two declarations would be equivalent:
f x = x + 5
f = \x -> x + 5
Both define a function with one parameter x that returns a number greater than x by 5.
I wanted to add to Fyodor’s answer by saying that this is a slightly unusual way to write this - it’s making explicit that semOp l returns a lambda. The following are all valid and equivalent ways to write this function’s beginning:
semOp l m = case l of ..
semOp l = \m -> case l of ..
semOp = \l -> \m -> case l of ..
semOp = \l m -> case l of ..
You might be most used to the first version, but in some languages like Haskell these can have slightly difference performance impacts - but this isn’t something for you to worry about, particularly in Elm as far as I understand.
I'm trying to write a function that creates a list of powers of a given number.
An example:
powList(2,5) = [0, 2, 4, 8, 16, 32]
Here is the code I already wrote:
let rec powList (x,n) =
if n = 0 then []
else (let a = let rec power (x, n) =
if n = 0 then 1
else x * power (x, n-1) in a) ::: powList(x, n-1);;
and this is the problem I get
Line 5, characters 31-32:
5 | else x * power (x, n-1) in a) ::: powList(x, n-1);;
^
Error: Syntax error: operator expected.
I'm only beginning to code in OCaml so I would be grateful for any help
Few generic remarks:
Don't define (recursive) functions inside recursive functions. Defining helper function in advance will make your code more readable and leave less room for syntax errors. For instance, lifting the definition of power outside of powList give you
let rec power x n =
if n = 0 then 1
else x * power x (n-1)
let rec powList (x,n) =
if n = 0 then []
else ( power ??? :: powList(x, n-1));;
Second, adding an element to a list is done with :: and not :::
Third, functions are generally curried in idiomatic OCaml code
let rec powList x n = ...
rather than
let rec powList (x,n)
because this opens more avenue for composition.
Fourth, your implementation is inefficient because it recomputes x^n at every step without fast exponentation. Consequently, your code ends up computing n * (n+1)/2 multiplications. Using fast exponentiation would reduce the number of multiplication to O(n log n). However the simpler version of using x^(n-1) to computes x yield only n multiplication:
let pow_list x n =
let rec pow_list x_power_n n =
if n = 0 then ...
else ...
in
pow_list ...
I am new to Idris. I am experimenting with types and my task is to make an "onion": a function that takes two arguments: a number and whatever and puts whatever into List nested such number of times.
For example, the result for mkOnion 3 "Hello World" should be [[["Hello World"]]].
I've made such a function, this is my code:
onionListType : Nat -> Type -> Type
onionListType Z b = b
onionListType (S a) b = onionListType a (List b)
mkOnionList : (x : Nat) -> y -> onionListType x y
mkOnionList Z a = a
mkOnionList (S n) a = mkOnionList n [a]
prn : (Show a) => a -> IO ();
prn a = putStrLn $ show a;
main : IO()
main = do
prn $ mkOnionList 3 4
prn $ mkOnionList 2 'a'
prn $ mkOnionList 5 "Hello"
prn $ mkOnionList 0 3.14
The result of program work:
[[[4]]]
[['a']]
[[[[["Hello"]]]]]
3.14
This is exactly what I need.
But when I do the same, but change Nat to Integer like this
onionListTypeI : Integer -> Type -> Type
onionListTypeI 0 b = b
onionListTypeI a b = onionListTypeI (a-1) (List b)
mkOnionListI : (x : Integer) -> y -> onionListTypeI x y
mkOnionListI 0 a = a
mkOnionListI n a = mkOnionListI (n-1) [a]
I get an error:
When checking right hand side of mkOnionListI with expected type
onionListTypeI 0 y
Type mismatch between
y (Type of a) and
onionListTypeI 0 y (Expected type)
Why does type checking fails?
I think this is because Integer can take negative values and Type can't be computed in case of negative values. If I am right, how does the compiler understand this?
You are right, that the type can't be computed. But that is because the onionListTypeI is not total. You can check this in the REPL
*test> :total onionListTypeI
Main.onionListTypeI is possibly not total due to recursive path:
Main.onionListTypeI, Main.onionListTypeI
(Or even better, demanding %default total in the source code, which would raise an error.)
Because the type constructor is not total, the compiler won't normalize onionListTypeI 0 y to y. It is not total, because of the case onionListTypeI a b = onionListTypeI (a-1) (List b). The compiler does only know that subtracting 1 from an Integer results to an Integer, but not which number exactly (unlike when doing it with a Nat). This is because arithmetic with Integer, Int, Double and the various Bits are defined with primary functions like prim__subBigInt. And if these functions wouldn't be blind, the compiler should have a problem with negative values, like you assumed.
What does this general grammar do?
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
the start symbol is S. I tried to generate string from this grammar and I got every binary numbers. but I think it does something specific.
S -> LR
L -> L0Y
L -> LX
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
L -> epsilon
R -> epsilon
terminals: 0,1
start: S
Let's split the grammar:
S -> LR
L -> L0Y
L -> LX
This will generate a string in the form L, string of X and 0Y, R.
X1 -> 1X
X0 -> 0X
X0 -> 1Y
Y1 -> 0Y
YR -> R
Treat X and Y as acting on the binary string: X will propagate to the right, then change a 0 to 1 and all subsequent 1s to 0s. In effect, a single X increments the binary number without changing its string length (or gets stuck).
A leading Y will rewrite the string of all 1s to all 0s (or gets stuck).
Treat the rules for L as the possible actions on the right part of the string. L => L0Y will reset the string from all ones to all zeroes and increase its length by one. L => LX will increment any other number, but fails if the value is at the maximum.
These two actions together are sufficient to generate (inefficiently) all strings of zeroes and ones (including the empty string).
L -> epsilon
R -> epsilon
will only clean up the sentinels.
one possible description of the language within four words:
set of all strings
Here's a simple program that blows my heap to Kingdom Come:
intersect n k z s rs c
| c == 23 = rs
| x == y = intersect (n+1) (k+1) (z+1) (z+s) (f : rs) (c+1)
| x < y = intersect (n+1) k (z+1) s rs c
| otherwise = intersect n (k+1) z s rs c
where x = (2*n*n) + 4 * n
y = (k * k + k )
f = (z, (x `div` 2), (z+s))
p = intersect 1 1 1 0 [] 0
main = do
putStr (show p)
What the program does is calculate the intersection of two infinite series, stopping when it reaches 23 elements. But that's not important to me.
What's interesting is that as far as I can tell, there shouldn't be much here that is sitting on the heap. The function intersect is recursives with all recursions written as tail calls. State is accumulated in the arguments, and there is not much of it. 5 integers and a small list of tuples.
If I were a betting person, I would bet that somehow thunks are being built up in the arguments as I do the recursion, particularly on arguments that aren't evaluated on a given recursion. But that's just a wild hunch.
What's the true problem here? And how does one fix it?
If you have a problem with the heap, run the heap profiler, like so:
$ ghc -O2 --make A.hs -prof -auto-all -rtsopts -fforce-recomp
[1 of 1] Compiling Main ( A.hs, A.o )
Linking A.exe ...
Which when run:
$ ./A.exe +RTS -M1G -hy
Produces an A.hp output file:
$ hp2ps -c A.hp
Like so:
So your heap is full of Integer, which indicates some problem in the accumulating parameters of your functions -- where all the Integers are.
Modifying the function so that it is strict in the lazy Integer arguments (based on the fact you never inspect their value), like so:
{-# LANGUAGE BangPatterns #-}
intersect n k !z !s rs c
| c == 23 = rs
| x == y = intersect (n+1) (k+1) (z+1) (z+s) (f : rs) (c+1)
| x < y = intersect (n+1) k (z+1) s rs c
| otherwise = intersect n (k+1) z s rs c
where x = (2*n*n) + 4 * n
y = (k * k + k )
f = (z, (x `div` 2), (z+s))
p = intersect 1 1 1 0 [] 0
main = do
putStr (show p)
And your program now runs in constant space with the list of arguments you're producing (though doesn't terminate for c == 23 in any reasonable time).
If it is OK to get the resulting list reversed, you can take advantage of Haskell's laziness and return the list as it is computed, instead of passing it recursively as an accumulating argument. Not only does this let you consume and print the list as it is being computed (thereby eliminating one space leak right there), you can also factor out the decision about how many elements you want from intersect:
{-# LANGUAGE BangPatterns #-}
intersect n k !z s
| x == y = f : intersect (n+1) (k+1) (z+1) (z+s)
| x < y = intersect (n+1) k (z+1) s
| otherwise = intersect n (k+1) z s
where x = (2*n*n) + 4 * n
y = (k * k + k )
f = (z, (x `div` 2), (z+s))
p = intersect 1 1 1 0
main = do
putStrLn (unlines (map show (take 23 p)))
As Don noted, we need to be careful so that accumulating arguments evaluate timely instead of building up big thunks. By making the argument z strict we ensure that all arguments will be demanded.
By outputting one element per line, we can watch the result being produced:
$ ghc -O2 intersect.hs && ./intersect
[1 of 1] Compiling Main ( intersect.hs, intersect.o )
Linking intersect ...
(1,3,1)
(3,15,4)
(10,120,14)
(22,528,36)
(63,4095,99)
(133,17955,232)
(372,139128,604)
(780,609960,1384)
...