Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Ocaml

Name: Anonymous 2010-10-07 14:26

So I've got an Ocaml assignment and I know shit about Ocaml. Wanna help a retard with his homework? I'll probably learn faster if I see examples. So, my tasks include:

1) Write a function that flattens a list of lists
2) Write a function that will count an object's occurences in a list
3) Define a function that will create a list containing a chosen number of duplicates of a certain object
4) Define a function that will square all numbers in a list
5) Write a function that will check if a list is a palindrome
6) Define a function that will return the length of a list
7) Define a function that will append two lists

Name: Anonymous 2010-10-08 6:56

Most of these are built-in in CL, but that's no surprise:

;;; 1
(defun mappend (fn list
                &rest otherlists
                &aux (list (copy-list list)) (otherlists (copy-list otherlists)))         
  (apply #'mapcan fn list otherlists))

(defun flatten (list)
  (mappend #'(lambda (e) (if (consp e) (flatten e) (list e))) list))
;CL-USER> (flatten '(1 (2 3 4) (5 (6 (7 8))) 9))
;(1 2 3 4 5 6 7 8 9)

;;; 2
#'count
;CL-USER> (count 1 '(1 2 3 1 0 1))
;3
;;; 3
#'make-list
;CL-USER> (make-list 5 :initial-element 'hi)
;(HI HI HI HI HI)
;;; 4
(defun square (x)
  (* x x))

(defun square-list (list)
  (mapcar #'square list))

;CL-USER> (square-list '(1 2 3))
;(1 4 9)

;;; 5
(defun palindromep (list)
  (equal list (reverse list)))

;CL-USER> (palindromep '(1 2 3 2 1))
;T
;CL-USER> (palindromep '(1 2 3 2))
;NIL

;;; 6
#'length

;CL-USER> (length '(a b c))
;3

;;; 7
#'append

;CL-USER> (append (list 1 2 3) '(a b c))
;(1 2 3 A B C)

However, if they weren't built-in, it's pretty easy to implement them.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List